spring六种种依赖注入方式

时间:2023-03-09 07:06:35
spring六种种依赖注入方式
平常的java开发中,程序员在某个类中需要依赖其它类的方法,则通常是new一个依赖类再调用类实例的方法,这种开发存在的问题是new的类实例不好统一管理,spring提出了依赖注入的思想,即依赖类不由程序员实例化,而是通过spring容器帮我们new指定实例并且将实例注入到需要该对象的类中。依赖注入的另一种说法是“控制反转”,通俗的理解是:平常我们new一个实例,这个实例的控制权是我们程序员,而控制反转是指new实例工作不由我们程序员来做而是交给spring容器来做。
spring有多种依赖注入的形式,下面仅介绍spring通过xml进行IOC配置的方式:
  • Set注入
这是最简单的注入方式,假设有一个SpringAction,类中需要实例化一个SpringDao对象,那么就可以定义一个private的SpringDao成员变量,然后创建SpringDao的set方法(这是ioc的注入入口):
  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. public void ok(){
  10. springDao.ok();
  11. }
  12. }
随后编写spring的xml文件,<bean>中的name属性是class属性的一个别名,class属性指类的全名,因为在SpringAction中有一个公共属性Springdao,所以要在<bean>标签中创建一个<property>标签指定SpringDao。<property>标签中的name就是SpringAction类中的SpringDao属性名,ref指下面<bean name="springDao"...>,这样其实是spring将SpringDaoImpl对象实例化并且调用SpringAction的setSpringDao方法将SpringDao注入:
  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两个参数值传进来:
  1. public class SpringAction {
  2. //注入对象springDao
  3. private SpringDao springDao;
  4. private User user;
  5. public SpringAction(SpringDao springDao,User user){
  6. this.springDao = springDao;
  7. this.user = user;
  8. System.out.println("构造方法调用springDao和user");
  9. }
  10. public void save(){
  11. user.setName("卡卡");
  12. springDao.save(user);
  13. }
  14. }
在XML文件中同样不用<property>的形式,而是使用<constructor-arg>标签,ref属性同样指向其它<bean>标签的name属性:
  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,就是参数位置:
  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>
  另一种是设置参数类型:
  1. <constructor-arg type="java.lang.String" ref=""/>
  • 静态工厂的方法注入
静态工厂顾名思义,就是通过调用静态工厂的方法来获取自己需要的对象,为了让spring管理所有对象,我们不能直接通过"工程类.静态方法()"来获取对象,而是依然通过spring注入的形式获取:
  1. package com.bless.springdemo.factory;
  2. import com.bless.springdemo.dao.FactoryDao;
  3. import com.bless.springdemo.dao.impl.FactoryDaoImpl;
  4. import com.bless.springdemo.dao.impl.StaticFacotryDaoImpl;
  5. public class DaoFactory {
  6. //静态工厂
  7. public static final FactoryDao getStaticFactoryDaoImpl(){
  8. return new StaticFacotryDaoImpl();
  9. }
  10. }
同样看关键类,这里我需要注入一个FactoryDao对象,这里看起来跟第一种注入一模一样,但是看随后的xml会发现有很大差别:
  1. public class SpringAction {
  2. //注入对象
  3. private FactoryDao staticFactoryDao;
  4. public void staticFactoryOk(){
  5. staticFactoryDao.saveFactory();
  6. }
  7. //注入对象的set方法
  8. public void setStaticFactoryDao(FactoryDao staticFactoryDao) {
  9. this.staticFactoryDao = staticFactoryDao;
  10. }
  11. }
Spring的IOC配置文件,注意看<bean name="staticFactoryDao">指向的class并不是FactoryDao的实现类,而是指向静态工厂DaoFactory,并且配置 factory-method="getStaticFactoryDaoImpl"指定调用哪个工厂方法:
  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>
  • 实例工厂的方法注入
实例工厂的意思是获取对象实例的方法不是静态的,所以你需要首先new工厂类,再调用普通的实例方法:
  1. public class DaoFactory {
  2. //实例工厂
  3. public FactoryDao getFactoryDaoImpl(){
  4. return new FactoryDaoImpl();
  5. }
  6. }
那么下面这个类没什么说的,跟前面也很相似,但是我们需要通过实例工厂类创建FactoryDao对象:
  1. public class SpringAction {
  2. //注入对象
  3. private FactoryDao factoryDao;
  4. public void factoryOk(){
  5. factoryDao.saveFactory();
  6. }
  7. public void setFactoryDao(FactoryDao factoryDao) {
  8. this.factoryDao = factoryDao;
  9. }
  10. }
最后看spring配置文件:
  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. <!--(4)此处获取对象的方式是从工厂类中获取实例方法-->
  7. <bean name="daoFactory" class="com.bless.springdemo.factory.DaoFactory"></bean>
  8. <bean name="factoryDao" factory-bean="daoFactory" factory-method="getFactoryDaoImpl"></bean>
  • 总结
Spring IOC注入方式用得最多的是(1)(2)种,多谢多练就会非常熟练。
        另外注意:通过Spring创建的对象默认是单例的,如果需要创建多实例对象可以在<bean>标签后面添加一个属性:
  1. <bean name="..." class="..." scope="prototype">
  1. Spring的依赖注入(接口注入)
  2. 2009-11-26 10:06 148人阅读 评论(0) 收藏 举报
  3. 这篇文章来谈谈《Spring Framework 开发参考手册》的3.3.3.1小节中的Lookup方法注入。
  4. 仔细看看文档,这种方法主要是用在Singleton的Object中使用非Singleton的Bean时,通过lookup-method的
  1. 那个方法来取得非Singleton的Bean。一般用的不多,在用这种定义之前最好想明白你的需求。
  2. · 先建立一个包:javamxj.spring.basic.lookup ,然后把以下5个文件放在这个包下。
  3. Hello.java.
  4. package javamxj.spring.basic.lookup;
  5. public interface Hello {
  6. public Random getRandom();
  7. public abstract Random createRandom();
  8. }
  9. Random.java
  10. package javamxj.spring.basic.lookup;
  11. public class Random {
  12. private int i = (int) (100 * Math.random());
  13. public void printRandom() {
  14. System.out.println("输出随机整数:  " + i);
  15. }
  16. }
  17. HelloAbstract.java
  18. package javamxj.spring.basic.lookup;
  19. public abstract class HelloAbstract implements Hello {
  20. private Random random;
  21. public Random getRandom() {
  22. return random;
  23. }
  24. public void setRandom(Random random) {
  25. this.random = random;
  26. }
  27. public abstract Random createRandom();
  28. }
  29. beans.xml
  30. <?xml version="1.0" encoding="GBK"?>
  31. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
  32. <beans>
  33. <bean id="ran" class="javamxj.spring.basic.lookup.Random" singleton="false"/>
  34. <bean id="hello" class="javamxj.spring.basic.lookup.HelloAbstract">
  35. <lookup-method name="createRandom" bean="ran"/>
  36. <property name="random">
  37. <ref local="ran"/>
  38. </property>
  39. </bean>
  40. </beans>
  41. Main.java
  42. package javamxj.spring.basic.lookup;
  43. import org.springframework.beans.factory.BeanFactory;
  44. import org.springframework.beans.factory.xml.XmlBeanFactory;
  45. import org.springframework.core.io.ClassPathResource;
  46. import org.springframework.core.io.Resource;
  47. public class Main {
  48. public static void main(String[] args) {
  49. Resource res = new ClassPathResource( "javamxj/spring/basic/lookup/beans.xml");
  50. BeanFactory ft = new XmlBeanFactory(res);
  51. Hello h = (Hello) ft.getBean("hello");
  52. Random r1 = h.getRandom();
  53. Random r2 = h.getRandom();
  54. System.out.println("没有采用Lookup方法注入:");
  55. System.out.println("Random 的两个实例指向同一个引用:" + (r1 == r2));
  56. r1.printRandom();
  57. r2.printRandom();
  58. Random r3 = h.createRandom();
  59. Random r4 = h.createRandom();
  60. System.out.println("/n采用Lookup方法注入:");
  61. System.out.println("Random 的两个实例指向同一个引用:" + (r3 == r4));
  62. r3.printRandom();
  63. r4.printRandom();
  64. }
  65. }
  66. 简单说明一下:
  67. · Hello是一个接口类,实现面向接口编程。
  68. · Random类用来输出随机整数。
  69. · HelloAbstract是一个抽象类,包含了一个属性:random,还包含一个抽象方法createRandom(),如果这个方法不是抽象的,spring会重写已有的实现。
  70. · beans.xml中定义了两个bean,ran指向Rondom类,注意它不是singleton的;hello指向HelloAbstract类,其中的random属性指向ran,createRandom方法也指向ran。
  71. · 在Main类中,Hello类分别利用getRandom()和createRandom()方法来调用Random类。
  72. · 这次需要将 spring-framework主目录/lib/cglib 目录中的cglib-nodep-2.1_2.jar加入到项目的 Libraries中,使用其中的动态代理。
  73. 运行结果:
  74. 没有采用Lookup方法注入:
  75. Random 的两个实例指向同一个引用:true
  76. 输出随机整数:  98
  77. 输出随机整数:  98
  78. 采用Lookup方法注入:
  79. Random 的两个实例指向同一个引用:false
  80. 输出随机整数:  51
  81. 输出随机整数:  26
  82. 本文来自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的效果是一样的。