bir*_*rdy 10 java spring-mvc autowired spring-3
我需要帮助理解背后的理念@Autowired
和@Service
.我有一个DAO @Service
和控制器定义,@Autowired
一切似乎很好,但是,我@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");
}
}
Run Code Online (Sandbox Code Playgroud)
调节器
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";
}
}
Run Code Online (Sandbox Code Playgroud)
以上一切都很好.但是,如果我想MyService
在POJO中使用那么它就不起作用了.例:
package com.springtest.mywork.pojos;
public class MyPojo {
@Autowired
MyService myService;
public void testFromPojo () {
myService.someDataAccessMethod(); //myService is still null
}
}
Run Code Online (Sandbox Code Playgroud)
弹簧配置:
<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>
Run Code Online (Sandbox Code Playgroud)
Aru*_*hny 16
这是因为您的POJO类不是由spring容器管理的.
@Autowire
注释仅适用于由spring管理的对象(即由spring容器创建).
在您的情况下,服务和控制器对象由spring管理,但您的POJO类不由spring管理,这就是为什么@Autowire
不会产生您期望的行为.
我注意到的另一个问题是,@Service
当spring具有@Repository
专门为此目的创建的注释时,您在DAO层中使用注释.
另外,不希望允许spring管理POJO类,因为通常它将是必须在容器外部创建的数据存储元件.
您能告诉我们POJO类的目的是什么以及为什么要在其中使用service
实例?
使用类路径扫描时,您必须与Spring通信要管理的类.这是用做@Service
注释,它关系(@Controller
,@Repository
,等).
如果您选择不对 bean进行注释,则必须在配置中明确声明它,就像使用dataSource
和jdbcTemplate
.
注释您的类意味着只有包中的那些类由Spring管理; 它允许您扫描包而无需管理该包中的所有类.
归档时间: |
|
查看次数: |
27227 次 |
最近记录: |