Spring中依赖注入的两种方式
Spring的核心机制就是依赖注入,那何谓依赖注入?举例说明:当某个java实例(调用者)需要另一个java实例(被调用者),也就是调用者依赖被调用者,Spring就是帮我们创建依赖对象,并把对象注入到调用者中。依赖注入有两种方式,分别是设值注入和构造注入,一般设值注入应用更多一些,下面通过实例来演示这两种方式。
一:设值注入
//调用者 public class UserAction { private Service service; private String name; private Date date; public void setService(Service service) { System.out.println("传入的对象是:"+service); this.service = service; } public void setName(String name) { System.out.println("传入的参数是:"+name); this.name = name; } public void setDate(Date date) { System.out.println("当前的时间是:"+date); this.date = date; } }
service类
public class Service { }
定义bean.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-4.0.xsd"> <bean id="ser" class="org.java.spring.Service" /> <bean id="da" class="java.util.Date" /> <bean id="user" class="org.java.spring.UserAction"> <property name="service" ref="ser" /> <property name="name" value="程序员是码农吗?" /> <property name="date" ref="da" /> </bean> </beans>
定义测试类
public class UserTest { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); } }
输出
传入的对象是:org.java.spring.Service@1341870
传入的参数是:程序员是码农吗?
当前的时间是:Mon Jan 12 23:37:15 CST 2015
二、构造注入
public class UserAction { private Service service; private String name; private Date date; //无参构造器 public UserAction() { System.out.println("创建UserAction的实例"); } //有参构造器 public UserAction(Service service,String name, Date date) { System.out.println("传入的对象是:"+service); System.out.println("传入的参数是:"+name); System.out.println("当前的时间是:"+date); this.service = service; this.name = name; this.date = date; } }
public class Service { //无参构造器 public Service(){ System.out.println("====创建Serice实例===="); } }
<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-4.0.xsd"> <bean id="ser" class="org.java.spring.Service" /> <bean id="da" class="java.util.Date" /> <bean id="user" class="org.java.spring.UserAction"> <constructor-arg value="程序员真的是码农吗?" /> <constructor-arg ref="da" /> <constructor-arg ref="ser" /> </bean> </beans>
输出
====创建Serice实例====
传入的对象是:org.java.spring.Service@13ad2d6
传入的参数是:程序员真的是码农吗?
当前的时间是:Tue Jan 13 00:15:35 CST 2015
【结论】
1、从上面可以看出在获取Spring容器时,容器会根据bean.xml文件,预初始化所有的bean,也就是创建对象,需要依赖某些对象的对象将依赖的对象注入到该对象中。
2、设值注入,是先通过无参构造器构建一个bean的实例,默认是单例,然后再调用setter方法将需要的参数注入,而构造注入是直接调用有参构造器(只能调一个),将参数注入,同时隐式创建bean实例。
情出自愿,事过无悔;不负遇见,不谈亏欠。

浙公网安备 33010602011771号