天天看点

依赖注入

使用属性setter方法注入

使用Field注入

注入依赖对象可以采用手工装配或自动装配,在实际应用中建议使用手工装配,因为自动装配会产生未知情况,开发人员无法预见最终的装配结果。

1.手工装配依赖对象

手工装配依赖对象,在这种方式中又有两种编程方式

1)在xml配置文件中,通过在bean节点下配置,如

<bean id="orderService" class="cn.itcast.service.OrderServicBean">

 <constructor-arg index="0" type="java.lang.String" value="xxx"/>//构造器注入

 <property name="name" value="zhao"/>//属性setter方法注入

</bean>

2)在java代码中使用 @Autowired或 @Resource注解方式进行装配。但我们需要在xml配置文件中配置以下信息:

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

    http://www.springframework.org/schema/context

    http://www.springframework.org/context/spring-context-2.5xsd">

    <context:annotation-config/>

</beans>

这个配置隐式注册了多个对注释进行解析处理的处理器:

AutowiredAnnotationBeanPostProcessor,ConnonAnnotationBeanPosrProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor

注: @Resource注解在spring安装目录的lib\j2ee\common-annotations.jar

2.自动装配依赖对象

Spring注解装配

打context就出现提示信息办法:

window->MyEclipse->Files and Editors->XML->XML catalog->

使用JdbcTemplate获取一条记录

@Service @Transactional

public class PersonServiceBean implements PersonService{

 private JdbcTemplate jdbcTemplate;

 @Resource

 public void setDataSource(DataSource dataSource){

  this.jdbcTemplate=new JdbcTemplate(dataSource);

 }

 public Person getPerson(Integer id){

  RowMapper rowMapper=new RowMapper(){

   public ObjectmapRow(Result rs,int rowNum)throws SQLException{

    Person person=new Person();

    person.setId(rs.getInt("id"));

    person.setName(rs.getString("name"));

    return person;

   }

  }

  return (Person)jdbcTemplate.queryForObject("select * from person where id=?",new Object[]{id},new int[]{java.sql.Type.INTEGER},rowMapper);

}

采用注解方式配置事务

<bean id="txManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

 <propertyname="dataSource" ref="dataSource"/>

<!--采用 @Transaction注解方式使用事务-->

<tx:annotation-driventransaction-manager="txManager"/>

public class presonServiceBean implements PresonService{

依赖注入-手工装配

在java代码中使用 @Autowried或 @Resource注解方式进行装配,这两个注解的区别是:

@Autowried默认按类型装配, @Resource默认按名称装配,当找不到与名称匹配的bean才会按类型装配。

@Autowired

private PersonDao persondao;//用于字段上

public void setOrderDao(OrderDao orderDao){//用于属性的setter方法上

 this.orderDao=orderDao;

 @Autowired 注解是按类型装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它required属性为false。如果我们使用按名称装配,可以结合 @Qualifier注解一起使用。如下:

 @Autowried @Qualifier("personDaoBean")

 private personDao person;

 @Resource注解我 @Autowired一样,也可以标注在字段或属性的setter方法上,但它默认按名称装配。担它默认按名称装配。名称可以通过 @Resource的name属性指定,如果没有指定name属性,当注解标注在字段上,即默认取字段的名称作为bean名称依赖对象,当注解标注在属性的setter方法上,即默认取属性名作为bean名称寻找依赖对象。

 @ Resource(name="personDaoBean")

 private PersonDao personDao;//用于字段上

 注意:如果没有指定name属性,并且按照默认的名称仍然找不到依赖对象时, @Resource注解会回退到按类型装配。但一旦指定了name属性,就只能按名称装配了。

 private void annotationInject() {

  for(String beanName : sigletons.keySet()){//循环所有的bean对象

   Object bean = sigletons.get(beanName); //获取bean对象

   if(bean!=null){//判断bean对象是否存在

    try {

     PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();//获取bean对象的属性描述

     for(PropertyDescriptor properdesc : ps){

      Method setter = properdesc.getWriteMethod();//获取属性的setter方法

      if(setter!=null && setter.isAnnotationPresent(ItcastResource.class)){//判断注解是否存在

       ItcastResource resource = setter.getAnnotation(ItcastResource.class);//取得注解

       Object value = null;

       if(resource.name()!=null && !"".equals(resource.name())){//得到name属性

        value = sigletons.get(resource.name());//取得bean对象

       }else{

        value = sigletons.get(properdesc.getName());//取得属性名称

        if(value==null){

         for(String key : sigletons.keySet()){

          if(properdesc.getPropertyType().isAssignableFrom(sigletons.get(key).getClass())){//获取属性描述

           value = sigletons.get(key);

           break;

          }

         }

        }        

       }

       setter.setAccessible(true);

       setter.invoke(bean, value);//把引用对象注入到属性

      }

     }

     Field[] fields = bean.getClass().getDeclaredFields();

     for(Field field : fields){

      if(field.isAnnotationPresent(ItcastResource.class)){

       ItcastResource resource = field.getAnnotation(ItcastResource.class);

       if(resource.name()!=null && !"".equals(resource.name())){

        value = sigletons.get(resource.name());

        value = sigletons.get(field.getName());

          if(field.getType().isAssignableFrom(sigletons.get(key).getClass())){

       field.setAccessible(true);//允许访问private字段

       field.set(bean, value);

    } catch (Exception e) {

     e.printStackTrace();

    }

上一篇: 依赖注入