我在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);

最佳答案

更改

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




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


您已经用NewServiceImpl注释了@Transactional,因此默认情况下spring将创建一个代理,该代理当然实现NewsService而不是NewsServiceImpl

08-03 13:19