Spring@Autowired注解与自动装配

来源:互联网 发布:遗传算法视频讲解 编辑:程序博客网 时间:2024/06/08 11:29

我们编写spring 框架的代码时候。一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量。并且要配套写上 get 和 set方法。

Spring 2.5 引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @Autowired的使用来消除 set ,get方法。

要实现我们要精简程序的目的。需要这样来处理: 
* 在applicationContext.xml中加入: 
<!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean 进行注入 -->       <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>  

Spring 通过一个 BeanPostProcessor 对 @Autowired 进行解析,所以要让 @Autowired 起作用必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。   

并且在applicationContext中将相应的<property></property>标签去掉:

<bean id="clasService" class="com.xxx.xxx.ClasServiceImpl">
</bean>     

Spring启动时,AutowiredAnnotationBeanPostProcessor会扫描所有的Bean,当发现其中有@Autowired注解时,就会找相应类型的Bean,并且实现注入。

@autowired 大大缩减了开发者的时间,是一个不错的新功能。 

参考:http://blog.csdn.net/heyutao007/article/details/5981555




原创粉丝点击