zoukankan      html  css  js  c++  java
  • 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。

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

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

    下面我们通过实例项目来看下spring注解注入的使用。

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

    然后新建CarDao类,给它添加@Repository注解,如下代码:

    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的实例中了。

    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中使用上面测试下注解注入:

    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的实例了。

    上面的例子非常简单,单纯的使用AnnotationConfigApplicationContext就可以了,但是在实际项目中情况往往没有这么简单,还是需要spring配置文件的。在spring配置文件中也可以通过下面的配置让spring自动扫描注解配置。

        <!-- 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的效果是一样的。

  • 相关阅读:
    物理课件开发记录之一2013年10月25日
    以as中的泛型数组举一例看帮助手册优化的好处
    flash的显示列表的机制探索一
    组合模式
    actionscript中重写注意事项
    用adobe air写一个金鱼监控程序
    adobe air桌面应用程序在前端显示,类似于暴风的总是在桌面的最上方
    windows7下的cmd命令之powercfg命令,不常用的
    设置默认访问项目的客户端的浏览器版本(IE版本)
    防火墙设置对外开放端口
  • 原文地址:https://www.cnblogs.com/doudou618/p/4325995.html
Copyright © 2011-2022 走看看