spring六种种依赖注入方式

 

日常的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>  
 
 
  • 总结
Spring IOC注入方式用得最多的是(1)(2)种,多谢多练就会很是熟练。
        另外注意:经过Spring建立的对象默认是单例的,若是须要建立多实例对象能够在<bean>标签后面添加一个属性:
Java代码   收藏代码
  1. <bean name="..." class="..." scope="prototype">  
 

 

Java代码   收藏代码
  1. Spring的依赖注入(接口注入)  
  2. 2009-11-26 10:06 148人阅读 评论(0) 收藏 举报  
  3.   这篇文章来谈谈《Spring Framework 开发参考手册》的3.3.3.1小节中的Lookup方法注入。  
  4.    
  5.   仔细看看文档,这种方法主要是用在Singleton的Object中使用非Singleton的Bean时,经过lookup-method的  
Java代码   收藏代码
  1. 那个方法来取得非Singleton的Bean。通常用的很少,在用这种定义以前最好想明白你的需求。  
  2.    
  3.    
  4. · 先创建一个包:javamxj.spring.basic.lookup ,而后把如下5个文件放在这个包下。  
  5.    
  6. Hello.java.   
  7. package javamxj.spring.basic.lookup;  
  8. public interface Hello {  
  9.     public Random getRandom();  
  10.     public abstract Random createRandom();  
  11. }  
  12.    
  13.    
  14. Random.java  
  15.    
  16. package javamxj.spring.basic.lookup;  
  17. public class Random {  
  18.     private int i = (int) (100 * Math.random());  
  19.     public void printRandom() {  
  20.         System.out.println("输出随机整数:  " + i);  
  21.     }  
  22. }  
  23.    
  24.    
  25. HelloAbstract.java   
  26. package javamxj.spring.basic.lookup;  
  27. public abstract class HelloAbstract implements Hello {  
  28.     private Random random;  
  29.     public Random getRandom() {  
  30.         return random;  
  31.     }  
  32.     public void setRandom(Random random) {  
  33.         this.random = random;  
  34.     }  
  35.     public abstract Random createRandom();  
  36. }  
  37.    
  38.    
  39. beans.xml   
  40. <?xml version="1.0" encoding="GBK"?>  
  41. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
  42. <beans>  
  43.     <bean id="ran" class="javamxj.spring.basic.lookup.Random" singleton="false"/>  
  44.       
  45.     <bean id="hello" class="javamxj.spring.basic.lookup.HelloAbstract">  
  46.         <lookup-method name="createRandom" bean="ran"/>  
  47.         <property name="random">  
  48.             <ref local="ran"/>  
  49.         </property>  
  50.     </bean>  
  51.       
  52. </beans>  
  53.    
  54.    
  55. Main.java  
  56.    
  57. package javamxj.spring.basic.lookup;  
  58. import org.springframework.beans.factory.BeanFactory;  
  59. import org.springframework.beans.factory.xml.XmlBeanFactory;  
  60. import org.springframework.core.io.ClassPathResource;  
  61. import org.springframework.core.io.Resource;  
  62. public class Main {  
  63.     public static void main(String[] args) {  
  64.         Resource res = new ClassPathResource( "javamxj/spring/basic/lookup/beans.xml");  
  65.         BeanFactory ft = new XmlBeanFactory(res);  
  66.         Hello h = (Hello) ft.getBean("hello");  
  67.         Random r1 = h.getRandom();  
  68.         Random r2 = h.getRandom();  
  69.         System.out.println("没有采用Lookup方法注入:");  
  70.         System.out.println("Random 的两个实例指向同一个引用:" + (r1 == r2));  
  71.         r1.printRandom();  
  72.         r2.printRandom();  
  73.         Random r3 = h.createRandom();  
  74.         Random r4 = h.createRandom();  
  75.         System.out.println("/n采用Lookup方法注入:");  
  76.         System.out.println("Random 的两个实例指向同一个引用:" + (r3 == r4));  
  77.         r3.printRandom();  
  78.         r4.printRandom();  
  79.     }  
  80. }    
  81.    
  82.    
  83. 简单说明一下:  
  84.    
  85. · Hello是一个接口类,实现面向接口编程。  
  86.    
  87. · Random类用来输出随机整数。  
  88.    
  89. · HelloAbstract是一个抽象类,包含了一个属性:random,还包含一个抽象方法createRandom(),若是这个方法不是抽象的,spring会重写已有的实现。  
  90.    
  91. · beans.xml中定义了两个bean,ran指向Rondom类,注意它不是singleton的;hello指向HelloAbstract类,其中的random属性指向ran,createRandom方法也指向ran。  
  92.    
  93. · 在Main类中,Hello类分别利用getRandom()和createRandom()方法来调用Random类。  
  94.    
  95. · 此次须要将 spring-framework主目录/lib/cglib 目录中的cglib-nodep-2.1_2.jar加入到项目的 Libraries中,使用其中的动态代理。  
  96.    
  97.    
  98. 运行结果:  
  99.    
  100. 没有采用Lookup方法注入:  
  101. Random 的两个实例指向同一个引用:true  
  102. 输出随机整数:  98  
  103. 输出随机整数:  98  
  104.    
  105. 采用Lookup方法注入:  
  106. Random 的两个实例指向同一个引用:false  
  107. 输出随机整数:  51  
  108. 输出随机整数:  26  
  109.   
  110. 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/javamxj/archive/2005/08/17/456600.aspx  

 个人理解:接口注入实际上是,经过配置Spring的lookup-method,及返回值 ,能够返回接口中方法的返回值而不须要实现接口中的抽象方法

注解注入顾名思义就是经过注解来实现注入,Spring和注入相关的常见注解有Autowired、Resource、Qualifier、Service、Controller、Repository、Component。java

  • Autowired是自动注入,自动从spring的上下文找到合适的bean来注入
  • Resource用来指定名称注入
  • Qualifier和Autowired配合使用,指定bean的名称
  • Service,Controller,Repository分别标记类是Service层类,Controller层类,数据存储层的类,spring扫描注解配置时,会标记这些类要生成bean。
  • Component是一种泛指,标记类是组件,spring扫描注解配置时,会标记这些类要生成bean。

上面的Autowired和Resource是用来修饰字段,构造函数,或者设置方法,并作注入的。而Service,Controller,Repository,Component则是用来修饰类,标记这些类要生成bean。node

下面咱们经过实例项目来看下spring注解注入的使用。mysql

首先新建一个maven项目,并在pom中添加spring相关的依赖,若是不知道添加那些依赖,请参照上一篇文章。程序员

而后新建CarDao类,给它添加@Repository注解,以下代码:spring

package cn.outofmemory.helloannotation; import org.springframework.stereotype.Repository; @Repository public class CarDao { public void insertCar(String car) { String insertMsg = String.format("inserting car %s", car); System.out.println(insertMsg); } }

新建CarService类,并给该类标注@Service注解,在这个类中定义CarDao的字段,并经过Autowired来修饰此字段,这样上面定义的CarDao类的实例就会自动注入到CarService的实例中了。sql

package cn.outofmemory.helloannotation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CarService { @Autowired private CarDao carDao; public void addCar(String car) { this.carDao.insertCar(car); } }

注意:Autowired注解有一个能够为空的属性required,能够用来指定字段是不是必须的,若是是必需的,则在找不到合适的实例注入时会抛出异常。编程

下面咱们在App.java中使用上面测试下注解注入:app

package cn.outofmemory.helloannotation; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { ApplicationContext appContext = new AnnotationConfigApplicationContext("cn.outofmemory.helloannotation"); CarService service = appContext.getBean(CarService.class); service.addCar("宝马"); } }

在上面的main方法中首先咱们初始化了appContext,他是AnnotationConfigApplicationContext,它的构造函数接受一个package的名称,来限定要扫描的package。而后就能够经过appContext的getBean方法得到CarService的实例了。less

上面的例子很是简单,单纯的使用AnnotationConfigApplicationContext就能够了,可是在实际项目中状况每每没有这么简单,仍是须要spring配置文件的。在spring配置文件中也能够经过下面的配置让spring自动扫描注解配置。dom

    <!-- bean annotation driven --> <context:annotation-config /> <context:component-scan base-package="cn.outofmemory.helloannotation" > </context:component-scan>

下面咱们看下混合使用spring配置和注解的例子,首先在项目中添加source folder,src/main/resources,并添加spring.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!-- bean annotation driven --> <context:annotation-config /> <context:component-scan base-package="cn.outofmemory.helloannotation" > </context:component-scan> <bean id="sqliteCarDao" class="cn.outofmemory.helloannotation.CarDao" > <constructor-arg name="driver" value="sqlite"/> </bean> </beans>

在上面的配置文件中,咱们经过context:annotation-config和context:component-sacn节点来指定要扫描注解注入,而后又定义了一个id为sqliteCarDao的bean,它的构造函数的driver值为sqlite。

咱们修改下App.java使用xml配置文件,再运行下App看下会怎样。

package cn.outofmemory.helloannotation; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { //ApplicationContext appContext = new AnnotationConfigApplicationContext("cn.outofmemory.helloannotation"); ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring.xml"); CarService service = appContext.getBean(CarService.class); service.addCar("宝马"); } }

运行程序发现输出为:inserting car 宝马 into mysql,显然CarService自动注入的CarDao使用了默认构造函数构造的实例。是否能够经过注解指定使用spring.xml中配置的sqliteCarDao呢?

咱们能够修改下CarService类,经过Qualifier注解来指定要使用的bean的名字。

以下,在指定Autowired注解时,同时指定Qualifier注解指定bean的名字

    @Autowired @Qualifier("sqliteCarDao") private CarDao carDao;

从新运行下App.java 此次输出的是inserting car 宝马 into sqlite,此次使用了spring.xml中配置的bean了。

在文中开头咱们还提到了Resouce注解,这个注解能够指定名字注入,咱们再次修改下CarService类:

    @Resource(name="sqliteCarDao") private CarDao carDao;

javax.annotation.Resource注解实现的效果和@Autowired+@Qualifier的效果是同样的。

相关文章
相关标签/搜索