【问题标题】:No qualifying bean of type [service.NewsServiceImpl] is defined没有定义 [service.NewsServiceImpl] 类型的限定 bean
【发布时间】:2017-12-23 06:34:13
【问题描述】:

我在 Spring MVC 中有一个错误。

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [service.NewsServiceImpl] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:333)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1088)
at controller.Testing.main(Testing.java:24)

NewsDAImpl 代码为:

@Repository 
public class NewsDAImpl implements NewsDA {

@PersistenceContext
private EntityManager context;  

@Override
public News ... Some Other Codes

我的 NewsServiceImpl 类:

@Service
@Transactional
public class NewsServiceImpl implements NewsService{

@Autowired
private NewsDAImpl newsDa;

@Override
public News ... Some Other Codes

我编写了具有静态 void main 的控制器,仅用于测试。 因为我写了这个:

ApplicationContext context = new AnnotationConfigApplicationContext(ProjectConfig.class);

然后我就用 getBean 方法获取新闻服务:

NewsServiceImpl service = context.getBean(NewsServiceImpl.class);

【问题讨论】:

  • 你的ProjectConfig好吗?
  • 永远不要对实现进行编码 - 对接口进行编码,因此不要在 impl 上使用 DI,而是使用接口。

标签: java spring hibernate spring-mvc spring-boot


【解决方案1】:

改变

NewsServiceImpl service = context.getBean(NewsServiceImpl.class);

到

NewsService service = context.getBean(NewsService.class);

你有NewServiceImpl 用@Transactional 注释,所以默认情况下spring 会创建一个代理,当然实现NewsService 而不是NewsServiceImpl。

【讨论】:

    猜你喜欢
    • 2018-07-25
    • 2016-06-28
    • 2016-01-12
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多