@Autowired和@Service在控制器上工作,但不在其他程序包中工作
问题内容:
我需要帮助来了解@Autowired
and 背后的概念@Service
。我用@Service
和定义了一个DAO
,@Autowired
并且一切正常,但是,我@Autowired
在不同的类中使用了相同的DAO ,但它不起作用。
例:
服务
@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";
}
}
以上所有工作正常。但是,如果我想MyService
在POJO中使用,那就行不通了。例:
package com.springtest.mywork.pojos;
public class MyPojo {
@Autowired
MyService myService;
public void testFromPojo () {
myService.someDataAccessMethod(); //myService is still null
}
}
弹簧配置:
<beans>
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<context:component-scan base-package="com.springtest.mywork" />
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mydb" />
<property name="username" value="hello" />
<property name="password" value="what" />
</bean>
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
</beans>
问题答案:
这是因为您的POJO类不是由spring容器管理的。
@Autowire
注解仅对那些由spring管理(即由spring容器创建)的对象起作用。
在您的情况下,服务和控制器对象由spring管理,但POJO类不是由spring管理的,这就是为什么@Autowire
不会产生您期望的行为的原因。
我注意到的另一个问题是,@Service
当spring具有@Repository
专门为此目的创建的注释时,您正在DAO层中使用注释。
同样不希望允许spring管理POJO类,因为通常它将是必须在容器外部创建的数据存储元素。
您能告诉我们POJO类的用途是什么,为什么要使用该service
实例吗?