@Autowired和@Service在控制器上工作,但不是从不同的包中工作

我需要帮助理解@Autowired@Service背后的概念。 我有一个用@Service@Autowired控制器定义的DAO,一切似乎都很好,但是,我在不同的类中使用相同的@Autowired然后它不起作用。

例:

服务

 @Service public class MyService { private JdbcTemplate jdbcTemplate; @Autowired public void setDataSource (DataSource myDataSource) { this.jdbcTemplate = new JdbcTemplate(myDataSource); } public void testUpdate(){ jdbcTemplate.update("some query"); } } 

调节器

 package com.springtest.mywork.controller; @Controller @RequestMapping(value = "/test.html") public class MyController { @Autowired MyService myService; @RequestMapping(method = RequestMethod.GET) public String test(Model model) { systemsService.testUpdate(); return "view/test"; } } 

以上都很好。 但是,如果我想在POJO中使用MyService ,那么它就不起作用了。 例:

 package com.springtest.mywork.pojos; public class MyPojo { @Autowired MyService myService; public void testFromPojo () { myService.someDataAccessMethod(); //myService is still null } } 

Spring配置:

                  

这是因为您的POJO类不是由spring容器管理的。

@Autowire注释仅适用于由spring管理的对象(即由spring容器创建)。

在您的情况下,服务和控制器对象由spring管理,但您的POJO类不由spring管理,这就是为什么@Autowire不会产生您期望的行为。

我注意到的另一个问题是,当spring具有专门为此目的创建的@Repository注释时,您在DAO层中使用@Service注释。

另外,不希望允许spring管理POJO类,因为通常它将是必须在容器外部创建的数据存储元件。

您能告诉我们POJO类的目的是什么以及为什么使用service实例?

使用类路径扫描时,您必须与Spring通信要管理的类。 这是使用@Service注释及其关系( @Controller@Repository等)完成的。

如果您选择注释bean,则必须在配置中显式声明它,就像使用dataSourcejdbcTemplate

注释您的类意味着只有包中的那些类由Spring管理; 它允许您扫描包而无需管理该包中的所有类。

在applicationContext.xml文件中包含它

  

您可以实现此操作以在POJO类中使用spring-managed bean。

http://www.javacodegeeks.com/2015/03/using-spring-managed-bean-in-non-managed-object.html

检查配置文件中的上下文组件扫描