spring依赖注入

来源:互联网 发布:股票持仓软件 编辑:程序博客网 时间:2024/06/06 08:30

平常的java开发中,程序员在某个类中需要依赖其它类的方法,则通常是new一个依赖类再调用类实例的方法,这种开发存在的问题是new的类实例不好统一管理,spring提出了依赖注入的思想,即依赖类不由程序员实例化,而是通过spring容器帮我们new指定实例并且将实例注入到需要该对象的类中。依赖注入的另一种说法是“控制反转”,通俗的理解是:平常我们new一个实例,这个实例的控制权是我们程序员,而控制反转是指new实例工作不由我们程序员来做而是交给spring容器来做。

spring有多种依赖注入的形式,下面仅介绍spring通过xml进行IOC配置的方式:
  • Set注入
这是最简单的注入方式,假设有一个SpringAction,类中需要实例化一个SpringDao对象,那么就可以定义一个private的SpringDao成员变量,然后创建SpringDao的set方法(这是ioc的注入入口):
Java代码  收藏代码
  1. package com.bless.springdemo.action;  
  2. public class SpringAction {  
  3.         //注入对象springDao  
  4.     private SpringDao springDao;  
  5.         //一定要写被注入对象的set方法  
  6.         public void setSpringDao(SpringDao springDao) {  
  7.         this.springDao = springDao;  
  8.     }  
  9.   
  10.         public void ok(){  
  11.         springDao.ok();  
  12.     }  
  13. }  

随后编写spring的xml文件,<bean>中的name属性是class属性的一个别名,class属性指类的全名,因为在SpringAction中有一个公共属性Springdao,所以要在<bean>标签中创建一个<property>标签指定SpringDao。<property>标签中的name就是SpringAction类中的SpringDao属性名,ref指下面<bean name="springDao"...>,这样其实是spring将SpringDaoImpl对象实例化并且调用SpringAction的setSpringDao方法将SpringDao注入
Java代码  收藏代码
  1. <!--配置bean,配置后该类由spring管理-->  
  2.     <bean name="springAction" class="com.bless.springdemo.action.SpringAction">  
  3.         <!--(1)依赖注入,配置当前类中相应的属性-->  
  4.         <property name="springDao" ref="springDao"></property>  
  5.     </bean>  
  6. <bean name="springDao" class="com.bless.springdemo.dao.impl.SpringDaoImpl"></bean>  
  

  • 构造器注入
这种方式的注入是指带有参数的构造函数注入,看下面的例子,我创建了两个成员变量SpringDao和User,但是并未设置对象的set方法,所以就不能支持第一种注入方式,这里的注入方式是在SpringAction的构造函数中注入,也就是说在创建SpringAction对象时要将SpringDao和User两个参数值传进来:
Java代码  收藏代码
  1. public class SpringAction {  
  2.     //注入对象springDao  
  3.     private SpringDao springDao;  
  4.     private User user;  
  5.       
  6.     public SpringAction(SpringDao springDao,User user){  
  7.         this.springDao = springDao;  
  8.         this.user = user;  
  9.         System.out.println("构造方法调用springDao和user");  
  10.     }  
  11.           
  12.         public void save(){  
  13.         user.setName("卡卡");  
  14.         springDao.save(user);  
  15.     }  
  16. }  
 
在XML文件中同样不用<property>的形式,而是使用<constructor-arg>标签,ref属性同样指向其它<bean>标签的name属性:
Xml代码  收藏代码
  1. <!--配置bean,配置后该类由spring管理-->  
  2.     <bean name="springAction" class="com.bless.springdemo.action.SpringAction">  
  3.         <!--(2)创建构造器注入,如果主类有带参的构造方法则需添加此配置-->  
  4.         <constructor-arg ref="springDao"></constructor-arg>  
  5.         <constructor-arg ref="user"></constructor-arg>  
  6.     </bean>  
  7.         <bean name="springDao" class="com.bless.springdemo.dao.impl.SpringDaoImpl"></bean>  
  8.          <bean name="user" class="com.bless.springdemo.vo.User"></bean>  
  解决构造方法参数的不确定性,你可能会遇到构造方法传入的两参数都是同类型的,为了分清哪个该赋对应值,则需要进行一些小处理:
下面是设置index,就是参数位置:
Xml代码  收藏代码
  1. <bean name="springAction" class="com.bless.springdemo.action.SpringAction">  
  2.         <constructor-arg index="0" ref="springDao"></constructor-arg>  
  3.         <constructor-arg index="1" ref="user"></constructor-arg>  
  4.     </bean>  
  另一种是设置参数类型:
Xml代码  收藏代码
  1. <constructor-arg type="java.lang.String" ref=""/>  
 
  • 静态工厂的方法注入
静态工厂顾名思义,就是通过调用静态工厂的方法来获取自己需要的对象,为了让spring管理所有对象,我们不能直接通过"工程类.静态方法()"来获取对象,而是依然通过spring注入的形式获取:
Java代码  收藏代码
  1. package com.bless.springdemo.factory;  
  2.   
  3. import com.bless.springdemo.dao.FactoryDao;  
  4. import com.bless.springdemo.dao.impl.FactoryDaoImpl;  
  5. import com.bless.springdemo.dao.impl.StaticFacotryDaoImpl;  
  6.   
  7. public class DaoFactory {  
  8.     //静态工厂  
  9.     public static final FactoryDao getStaticFactoryDaoImpl(){  
  10.         return new StaticFacotryDaoImpl();  
  11.     }  
  12. }  

同样看关键类,这里我需要注入一个FactoryDao对象,这里看起来跟第一种注入一模一样,但是看随后的xml会发现有很大差别:
Java代码  收藏代码
  1.  public class SpringAction {  
  2.         //注入对象  
  3.     private FactoryDao staticFactoryDao;  
  4.       
  5.     public void staticFactoryOk(){  
  6.         staticFactoryDao.saveFactory();  
  7.     }  
  8.     //注入对象的set方法  
  9.     public void setStaticFactoryDao(FactoryDao staticFactoryDao) {  
  10.         this.staticFactoryDao = staticFactoryDao;  
  11.     }  
  12. }  
 
Spring的IOC配置文件,注意看<bean name="staticFactoryDao">指向的class并不是FactoryDao的实现类,而是指向静态工厂DaoFactory,并且配置 factory-method="getStaticFactoryDaoImpl"指定调用哪个工厂方法
Xml代码  收藏代码
  1. <!--配置bean,配置后该类由spring管理-->  
  2.     <bean name="springAction" class="com.bless.springdemo.action.SpringAction" >  
  3.         <!--(3)使用静态工厂的方法注入对象,对应下面的配置文件(3)-->  
  4.         <property name="staticFactoryDao" ref="staticFactoryDao"></property>  
  5.                 </property>  
  6.     </bean>  
  7.     <!--(3)此处获取对象的方式是从工厂类中获取静态方法-->  
  8.     <bean name="staticFactoryDao" class="com.bless.springdemo.factory.DaoFactory" factory-method="getStaticFactoryDaoImpl"></bean>  
  9.       
 


  • 实例工厂的方法注入
实例工厂的意思是获取对象实例的方法不是静态的,所以你需要首先new工厂类,再调用普通的实例方法:
Java代码  收藏代码
  1. public class DaoFactory {  
  2.     //实例工厂  
  3.     public FactoryDao getFactoryDaoImpl(){  
  4.         return new FactoryDaoImpl();  
  5.     }  
  6. }  

那么下面这个类没什么说的,跟前面也很相似,但是我们需要通过实例工厂类创建FactoryDao对象:
Java代码  收藏代码
  1. public class SpringAction {  
  2.     //注入对象  
  3.     private FactoryDao factoryDao;  
  4.       
  5.     public void factoryOk(){  
  6.         factoryDao.saveFactory();  
  7.     }  
  8.   
  9.     public void setFactoryDao(FactoryDao factoryDao) {  
  10.         this.factoryDao = factoryDao;  
  11.     }  
  12. }  
 
最后看spring配置文件:
Xml代码  收藏代码
  1. <!--配置bean,配置后该类由spring管理-->  
  2.     <bean name="springAction" class="com.bless.springdemo.action.SpringAction">  
  3.         <!--(4)使用实例工厂的方法注入对象,对应下面的配置文件(4)-->  
  4.         <property name="factoryDao" ref="factoryDao"></property>  
  5.     </bean>  
  6.       
  7.     <!--(4)此处获取对象的方式是从工厂类中获取实例方法-->  
  8.     <bean name="daoFactory" class="com.bless.springdemo.factory.DaoFactory"></bean>  
  9.     <bean name="factoryDao" factory-bean="daoFactory" factory-method="getFactoryDaoImpl"></bean>  
 
自动装配注入:
自动装配有三种模式:byType、byName和constructor。
有时,并没有必要显式地在Bean定义中定义依赖项;可以让Spring容器自动地向Bean中注入依赖项。该过程被称为自动装配(autowiring)。在开发过程中该功能是非常有用的,因为有时Bean的定义需要随着代码库的演变而更新。
方式以:在xml实现自动装配
Car.java
public class Car{
   public void start(){
   System.out.println("starting car....")
}
}
public class user{
    private Car car;
    public void setCar(Car car){
     this.car=car;
}
    public void satrtCar(){
    car.start;
}
}

xml配置文件
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans   
           http://www.springframework.org/schema/beans/spring-beans.xsd">  
             
       <bean id="car" class="com.zzj.bean.Car"></bean>  
       <bean id="user" class="com.zzj.bean.User" autowire="byName"></bean>  
</beans>  

测试
public static void main(String[] args) {  
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
        User user = (User) context.getBean("user");  
        user.startCar();  
    }  
注意:哟让Spring 容器自动装配 bean 需要提供一个参考 这个参考就是bean的autowire属性
自动装配中的三个方式
1:byName :因为spring容器中bean的名字是唯一的 所以不会产生歧义 推荐使用这个方式
2:byType:根据类型自动装配 在spring容器中可能会找到多个跟需要注入的bean的类型相同的bean 所提会产生歧义 spring容器不知道要注入那个bean 这时会抛出异常
3:根据构造器自动装配(constructor)这中方式比较复杂 不做分析


方式二使用注解实现自动装配

       @Component
public class Car {
    public  void startCar(){
        System.out.println("Car starting....");
    }
}
@Component
public class User {
    @Autowired
    private Car car;//自动装配  此时setter方法可以省掉。


    public void  statrtCar(){
        car.startCar();
    }
}
xml配置 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">


<context:component-scan base-package="ch2.autowired"></context:component-scan>
<context:annotation-config></context:annotation-config>
</beans>
注:@Autowired是spring自带的注解,也可以使用Java原生的注解:@Resource。推荐使用@Resource,更具移植性。


0 0
原创粉丝点击