我们编写spring 框架的代码时候。一直遵循是这样一个规则:所有在spring中注入的bean都建议定义成私有的域变量。并且要配套写上 get 和set方法。虽然可以通过eclipse等工具来自动生成。但是还是会引起程序阅读性上的不便。那么既然注解这么强大。是否可以也把他精简掉呢?当 然可以。
这个标签就是@Autowired,通过 @Autowired的使用来消除 set ,get方法
Spring 2.5 引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作
要实现我们要精简程序的目的。需要这样来处理:
1.在applicationContext.xml中加入:
<wbr><wbr><wbr><!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean进行注入 --><wbr><wbr><br><wbr><wbr><wbr><beanclass="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanP<wbr>ostProcessor"/></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>
2.* 修改在原来注入spirng容器中的bean的方法。
<wbr><wbr><wbr><wbr>在域变量上加上标签@Autowired,并且去掉 相应的get 和set方法</wbr></wbr></wbr></wbr>
3* 在applicatonContext.xml中 把原来 引用的<porpery>标签也去掉。
<wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><bean id="CountryService"class="com.firemax.test.service.CountryService"><br><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><property name="alcorTCountriesDAO"ref="AlcorTCountriesDAO" /><br><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><property name="alcorTProvincesDAO"ref="AlcorTProvincesDAO" /><br><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><property name="alcorTCitysDAO" ref="AlcorTCitysDAO"/><br><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><property name="alcotTDistrictDAO"ref="AlcotTDistrictDAO" /><br><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr></bean></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>
修改成
<wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><bean id="CountryService"class="com.firemax.test.service.CountryService"><br><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><br><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr></bean></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>
当然,我们也可以在构造函数上使用@Auwowired 注解 。如果构造函数有两个入参,分别是 bean1 和bean2,@Autowired 将分别寻找和它们类型匹配的 Bean,将它们作为 CountryService (Bean1bean1 ,Bean2 bean2) 的入参来创建 CountryService Bean。