spring @Autowired使用

来源:互联网 发布:什么是优化推广 编辑:程序博客网 时间:2024/05/19 11:45
通过 @Autowired的使用来消除 set ,get方法 - Spring 2.5 JPAhibernate 使用方法的点滴整理

我们编写spring 框架的代码时候。一直遵循是这样一个规则:所有在spring中注入的bean都建议定义成私有的域变量。并且要配套写上 get 和set方法。虽然可以通过eclipse等工具来自动生成。但是还是会引起程序阅读性上的不便。那么既然注解这么强大。是否可以也把他精简掉呢?

当 然可以。这个标签就是@Autowired

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

要实现我们要精简程序的目的。需要这样来处理:

* 在applicationContext.xml中加入:
   <!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean进行注入 -->  
   <beanclass="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>


* 修改在原来注入spirng容器中的bean的方法。
    在域变量上加上标签@Autowired,并且去掉 相应的get 和set方法

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
importorg.springframework.beans.factory.annotation.Autowired;
import com.firemax.test.hibernate.AlcorTCitys;
import com.firemax.test.hibernate.AlcorTCitysDAO;
import com.firemax.test.hibernate.AlcorTCountries;
import com.firemax.test.hibernate.AlcorTCountriesDAO;
import com.firemax.test.hibernate.AlcorTProvinces;
import com.firemax.test.hibernate.AlcorTProvincesDAO;
import com.firemax.test.hibernate.AlcotTDistrict;
import com.firemax.test.hibernate.AlcotTDistrictDAO;
public class CountryService {
    private static Log logger =LogFactory.getLog(CountryService.class);
    @Autowired
    private AlcorTCountriesDAO alcorTCountriesDAO;
    @Autowired
    private AlcorTProvincesDAO alcorTProvincesDAO;
    @Autowired
    privateAlcorTCitysDAO         alcorTCitysDAO;
    @Autowired
    privateAlcotTDistrictDAO      alcotTDistrictDAO;
    public CountryService(){
    }
    
    public void updateCountry(AlcorTCountries alcorTCountries ) throwsException{
        this.alcorTCountriesDAO.update(alcorTCountries);
    }
    ....
    //这里去掉了哪些DAO 变量的get 和set 方法。
}

* 在applicatonContext.xml中 把原来 引用的<porpery>标签也去掉。

        <bean id="CountryService"class="com.firemax.test.service.CountryService">
                 <property name="alcorTCountriesDAO"ref="AlcorTCountriesDAO" />
                 <property name="alcorTProvincesDAO"ref="AlcorTProvincesDAO" />
                 <property name="alcorTCitysDAO" ref="AlcorTCitysDAO"/>
                <property name="alcotTDistrictDAO"ref="AlcotTDistrictDAO" />
         </bean>

修改成

         <bean id="CountryService"class="com.firemax.test.service.CountryService">
                
        </bean>

当然,我们也可以在构造函数上使用@Auwowired 注解 。如果构造函数有两个入参,分别是 bean1 和bean2,@Autowired 将分别寻找和它们类型匹配的 Bean,将它们作为 CountryService (Bean1bean1 ,Bean2 bean2) 的入参来创建 CountryService Bean。

原创粉丝点击