我需要帮助理解背后的概念@Autowired
and @Service
。我有一个 DAO 定义为@Service
和控制器@Autowired
一切看起来都很好,但是,我使用相同的@Autowired
在不同的班级,那么它不起作用。
Example:
Service
@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有的时候DAO层的注解@Repository
为此目的专门创建的注释。
另外,也不希望允许 spring 管理 POJO 类,因为通常它是必须在容器外部创建的数据存储元素。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)