Spring之DI的配置使用

1.IoC容器的依赖含义

Spring IoC容器的依赖有两层含义:Bean依赖容器和容器注入Bean的依赖资源。
Bean依赖容器:也就是说Bean要依赖于容器,这里的依赖是指容器负责创建Bean并管理Bean的生命周期,正是由于由容器来控制创建Bean并注入依赖,也就是控制权被反转了,这也正是IoC名字的由来,此处的依赖是指Bean和容器之间的依赖关系。
容器注入Bean的依赖资源:容器负责注入Bean的依赖资源,依赖资源可以是Bean、外部文件、常量数据等,在Java中都反映为对象,并且由容器负责组装Bean之间的依赖关系,此处的依赖是指Bean之间的依赖关系,可以认为是传统类与类之间的“关联”、“聚合”、“组合”关系。

2.依赖注入的好处

1.动态替换Bean依赖对象,程序更灵活

替换Bean依赖对象,无需修改源文件。应用依赖注入后,由于可以采用配置文件方式实现,从而能随时动态的替换Bean的依赖对象,无需修改java源文件;

2.更好实践面向接口编程,代码更清晰

在Bean中只需指定依赖对象的接口,接口定义依赖对象完成的功能,通过容器注入依赖实现;

3.更好实践优先使用对象组合,而不是类继承

因为IoC容器采用注入依赖,也就是组合对象,从而更好的实践对象组合。
采用对象组合,Bean的功能可能由几个依赖Bean的功能组合而成,其Bean本身可能只提供少许功能或根本无任何功能,全部委托给依赖Bean,对象组合具有动态性,能更方便的替换掉依赖Bean,从而改变Bean功能;
而如果采用类继承,Bean没有依赖Bean,而是采用继承方式添加新功能,而且功能是在编译时就确定了,不具有动态性,而且采用类继承导致Bean与子Bean之间高度耦合,难以复用。

4.增加Bean可复用性

依赖于对象组合,Bean更可复用且复用更简单;

5.降低Bean之间耦合

由于我们完全采用面向接口编程,在代码中没有直接引用Bean依赖实现,全部引用接口,而且不会出现显示的创建依赖对象代码,而且这些依赖是由容器来注入,很容易替换依赖实现类,从而降低Bean与依赖之间耦合;

6.代码结构更清晰

要应用依赖注入,代码结构要按照规约方式进行书写,从而更好的应用一些最佳实践,因此代码结构更清晰。

3.Ioc容器3种依赖注入方式

1.构造器注入

容器实例化Bean时注入那些依赖,通过在Bean定义中指定构造器参数进行注入依赖,包括实例工厂方法参数注入依赖,但静态工厂方法参数不允许注入依赖;

可根据参数索引、参数类型、参数名称注入。但参数名注入是有限制的,需要使用在编译程序时打开调试模式(即在编译时使用“javac –g:vars”在class文件中生成变量调试信息,默认是不包含变量调试信息的,从而能获取参数名字,否则获取不到参数名字)或在构造器上使用@ConstructorProperties(java.beans.ConstructorProperties)注解来指定参数名。

BeanImpl3

package com.chensan.spring.chapter3;

import com.chensan.spring.chapter1.BeanApi;

public class BeanImpl3 implements BeanApi {
	private int index;
	private String message;
	
	//@java.beans.ConstructorProperties({"index", "message"})
	public BeanImpl3(int index, String message){
		this.index = index;
		this.message = message;
	}
	
	@Override
	public void sayHello() {
		System.out.println(index + " : " + message);
	}

}

bean3_1.xml

<!-- 通过构造器参数索引方式依赖注入 -->
<bean id="byIndex" class="com.chensan.spring.chapter3.BeanImpl3_1">
  <constructor-arg index="1" value="Constructor with parameter index"/>
  <constructor-arg index="0" value="4"/>
</bean>
  
<!-- 通过构造器参数类型方式依赖注入 -->
<bean id="byType" class="com.chensan.spring.chapter3.BeanImpl3_1">
  <constructor-arg type="java.lang.String" value="Constructor with parameter type"/>
  <constructor-arg type="int" value="2"/>
</bean>
  
<!-- 通过构造器参数名称方式依赖注入 -->
<bean id="byName" class="com.chensan.spring.chapter3.BeanImpl3_1">
  <constructor-arg name="index" value="3"/>
  <constructor-arg name="message" value="Constructor with parameter name"/>
</bean>

TestBean3_1

package com.chensan.spring.chapter3.test;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chensan.spring.chapter1.BeanApi;

public class TestBean3_1 {
	@Test
	public void testConstructorDependencyInject() {
	    BeanFactory beanFactory =  new ClassPathXmlApplicationContext("bean3_1.xml");
	    //获取根据参数索引依赖注入的Bean
	    BeanApi byIndex = beanFactory.getBean("byIndex", BeanApi.class);
	    byIndex.sayHello();
	    //获取根据参数类型依赖注入的Bean
	    BeanApi byType = beanFactory.getBean("byType", BeanApi.class);
	    byType.sayHello();
	    //获取根据参数名字依赖注入的Bean
	    BeanApi byName = beanFactory.getBean("byName", BeanApi.class);
	byName.sayHello();
	}
}
输出结果:

4 : Constructor with parameter index
2 : Constructor with parameter type
3 : Constructor with parameter name

至于静态工厂和实例化工厂的Bean定义请看前一篇。

2.setter注入

setter注入,是通过在通过构造器、静态工厂或实例工厂实例好Bean后,通过调用Bean类的setter方法进行注入依赖。

BeanImpl3_2

package com.chensan.spring.chapter3;

import com.chensan.spring.chapter1.BeanApi;

public class BeanImpl3_2 implements BeanApi {
	private int index;
	private String message;
	
	//setter方法 
    public void setIndex(int index) {
        this.index = index;
    }
    public void setMessage(String message) {
    	this.message = message;
    }
	
	@Override
	public void sayHello() {
		System.out.println(index + " :" + message);
	}

}
bean3_2.xml
<!-- 通过setter方式进行依赖注入 -->
<bean id="bean3_2" class="com.chensan.spring.chapter3.BeanImpl3_2">
  
</bean>
TestBean3_2
package com.chensan.spring.chapter3.test;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chensan.spring.chapter1.BeanApi;

public class TestBean3_2 {
	@Test
	public void testSetterDependencyInject() {
		BeanFactory beanFactory =  new ClassPathXmlApplicationContext("bean3_2.xml");
		//获取根据参数索引依赖注入的Bean
		BeanApi beanApi = beanFactory.getBean("bean3_2", BeanApi.class);
		beanApi.sayHello();
	}
}

知道如何配置了,但Spring如何知道setter方法?如何将值注入进去的呢?其实方法名是要遵守约定的,setter注入的方法名要遵循“JavaBean getter/setter 方法命名约定”:

         JavaBean:是本质就是一个POJO类,但具有一下限制:

         该类必须要有公共的无参构造器,如public HelloImpl4() {};

         属性为private访问级别,不建议public,如private String message;

         属性必要时通过一组setter(修改器)和getter(访问器)方法来访问

         setter方法,以“set” 开头,后跟首字母大写的属性名,如“setMesssage”,简单属性一般只有一个方法参数,方法返回值通常为“void”;

         getter方法,一般属性以“get”开头,对于boolean类型一般以“is”开头,后跟首字母大写的属性名,如“getMesssage”,“isOk”;

         还有一些其他特殊情况,比如属性有连续两个大写字母开头,如“URL”,则setter/getter方法为:“setURL”和“getURL”,其他一些特殊情况请参看“Java Bean”命名规范。

1.注入常量

<property name="message" value="Hello Spring setter Dependencyf Inject"></property>
或
<property name="index">
    <value>1</value>
</property>
从配置来看第一种更简洁。注意此处“value”中指定的全是字符串,由Spring容器将此字符串转换成属性所需要的类型,如果转换出错,将抛出相应的异常。
Spring容器目前能对各种基本类型把配置的String参数转换为需要的类型。
注:Spring类型转换系统对于boolean类型进行了容错处理,除了可以使用“true/false”标准的Java值进行注入,还能使用“yes/no”、“on/off”、“1/0”来代表“真/假”,所以大家在学习或工作中遇到这种类似问题不要觉得是人家配置错了,而是Spring容错做的非常好。

下面为布尔值类型的示例:

BeanImpl3_2_1

package com.chensan.spring.chapter3;

import com.chensan.spring.chapter1.BeanApi;

public class BeanImpl3_2_1 implements BeanApi {
	private boolean flag;
	
	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	@Override
	public void sayHello() {
		System.out.println("flag is " + flag);
	}
	
}

bean3_2_1.xml

<!-- boolean参数值可以用on/off -->
<bean id="bean3_2_1_1" class="com.chensan.spring.chapter3.BeanImpl3_2_1">
  <property name="flag" value="on"></property>
</bean>

<!-- boolean参数值可以用yes/no -->
<bean id="bean3_2_1_2" class="com.chensan.spring.chapter3.BeanImpl3_2_1">
  <property name="flag" value="yes"></property>
</bean>

<!-- boolean参数值可以用1/0 -->
<bean id="bean3_2_1_3" class="com.chensan.spring.chapter3.BeanImpl3_2_1">
  <property name="flag" value="1"></property>
</bean>
TestBean3_2_1

package com.chensan.spring.chapter3.test;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chensan.spring.chapter1.BeanApi;

public class TestBean3_2_1 {
	@Test
	public void testSetterDependencyInject() {
		BeanFactory beanFactory =  new ClassPathXmlApplicationContext("bean3_2_1.xml");
		//获取参数名称(注入常量)依赖注入的Bean
		BeanApi beanApi1 = beanFactory.getBean("bean3_2_1_1", BeanApi.class);
		beanApi1.sayHello();
		BeanApi beanApi2 = beanFactory.getBean("bean3_2_1_2", BeanApi.class);
		beanApi2.sayHello();
		BeanApi beanApi3 = beanFactory.getBean("bean3_2_1_3", BeanApi.class);
		beanApi3.sayHello();
	}
}

2.注入Bean ID

用于注入Bean的ID,ID是一个常量不是引用,且类似于注入常量,但提供错误验证功能。

BeanImpl3_3

package com.chensan.spring.chapter3;

import com.chensan.spring.chapter1.BeanApi;

public class BeanImpl3_3 implements BeanApi {
	private String id;

	public void setId(String id) {
		this.id = id;
	}

	@Override
	public void sayHello() {
		System.out.println("id = " + id);
	}

}
bean3_3.xml
<bean id="bean3_3_1" class="java.lang.String">
  <constructor-arg index="0" value="test"/>
</bean>

<bean id="bean3_3_2" class="java.lang.String">
  <constructor-arg index="0" value="test"/>
</bean>

<bean id="idrefBean1" class="com.chensan.spring.chapter3.BeanImpl3_3">
  <property name="id">
    <idref bean="bean3_3_1"/>
  </property>
</bean>

<bean id="idrefBean2" class="com.chensan.spring.chapter3.BeanImpl3_3">
  <property name="id"><idref local="bean2"/></property>
</bean> 

cvc-complex-type.3.2.2: Attribute 'local' is not allowed to appear in element 'idref'.

TestBean3_3

package com.chensan.spring.chapter3.test;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chensan.spring.chapter1.BeanApi;

public class TestBean3_3 {
	@Test
	public void testSetterDependencyInject() {
		BeanFactory beanFactory =  new ClassPathXmlApplicationContext("bean3_3.xml");
		//获取根据参数索引依赖注入的Bean 
		BeanApi beanApi = beanFactory.getBean("idrefBean1", BeanApi.class);
		beanApi.sayHello();
	}
}

id = bean3_3_1

能通过配置方式替换掉Bean方法,也就是通过配置改变Bean方法功能;

Spring不仅能注入简单类型数据,还能注入集合(Collection、无序集合Set、有序集合List)类型、数组(Array)类型、字典(Map)类型数据、Properties类型数据

1.注入集合

1.注入List

ListBean

package com.chensan.spring.chapter4;

import java.util.List;

public class ListBean {
	private List<String> values;
	
	public List<String> getValues() {
		return values;
	}

	public void setValues(List<String> values) {
		this.values = values;
	}
}
listBean.xml
<bean id="listBean" class="com.chensan.spring.chapter4.ListBean">
  <property name="values">
    <list>
      <value>1</value>
      <value>2</value>
      <value>3</value>
    </list>  
  </property>
</bean>
TestListBean
package com.chensan.spring.chapter4.test;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chensan.spring.chapter4.ListBean;

public class TestListBean {
	@Test
	public void testListInject() {
		BeanFactory beanFactory =  new ClassPathXmlApplicationContext("listBean.xml");
		ListBean beanImpl = beanFactory.getBean("listBean", ListBean.class);
		System.out.println(beanImpl.getValues());
		System.out.println(beanImpl.getValues().size());
		Assert.assertEquals(3, beanImpl.getValues().size());
	}
}

2.注入Set

SetBean

package com.chensan.spring.chapter4;

import java.util.Set;

public class SetBean {
	private Set<String> values;
	
	public Set<String> getValues() {
		return values;
	}
	
	public void setValues(Set<String> values) {
		this.values = values;
	}	
}
setBean.xml
<bean id="setBean" class="com.chensan.spring.chapter4.SetBean">
  <property name="values">
    <set>
      <value>1</value>
      <value>2</value>
      <value>3</value>
    </set>  
  </property>
</bean>
TestSetBean
package com.chensan.spring.chapter4.test;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chensan.spring.chapter4.SetBean;

public class TestSetBean {
	@Test
	public void testSetInject() {
		BeanFactory beanFactory =  new ClassPathXmlApplicationContext("setBean.xml");
		SetBean beanImpl = beanFactory.getBean("setBean", SetBean.class);
		System.out.println(beanImpl.getValues());
		System.out.println(beanImpl.getValues().size());
		Assert.assertEquals(3, beanImpl.getValues().size());
	}
}
3.注入Collection

CollectionBean

package com.chensan.spring.chapter4;

import java.util.Collection;

public class CollectionBean {
	private Collection<String> values;
	
	public Collection<String> getValues() {
		return values;
	}
	
	public void setValues(Collection<String> values) {
		this.values = values;
	}
}
collectionBean.xml
<bean id="collectionBean" class="com.chensan.spring.chapter4.CollectionBean">
  <property name="values">
    <set>
      <value>1</value>
      <value>2</value>
      <value>3</value>
    </set>
  </property>
</bean>
TestCollectionBean
package com.chensan.spring.chapter4.test;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chensan.spring.chapter4.CollectionBean;

public class TestCollectionBean {
	@Test
	public void testSetInject() {
		BeanFactory beanFactory =  new ClassPathXmlApplicationContext("collectionBean.xml");
		CollectionBean beanImpl = beanFactory.getBean("collectionBean", CollectionBean.class);
		System.out.println(beanImpl.getValues());
		System.out.println(beanImpl.getValues().size());
		Assert.assertEquals(3, beanImpl.getValues().size());
	}
}

由上面看List、Set、Collection注入的方式基本一致,只是注意注入类型的对应。

Collection类型是Set和List类型的基类型,所以使用<set>或<list>标签都可以进行注入,配置方式完全和以上配置方式一样,只是将测试类属性改成“Collection”类型.

2.注入数组

ArrayBean

package com.chensan.spring.chapter4;

public class ArrayBean {
	private String[] array;
	private String[][] array2;
	
	public String[] getArray() {
		return array;
	}
	public void setArray(String[] array) {
		this.array = array;
	}
	public String[][] getArray2() {
		return array2;
	}
	public void setArray2(String[][] array2) {
		this.array2 = array2;
	}
}
arraryBean.xml
<bean id="arrayBean" class="com.chensan.spring.chapter4.ArrayBean">
  <property name="array">
    <array>
      <value>1</value>
      <value>2</value>
    </array>
  </property>
  
  <property name="array2">
    <array>
      <array>
        <value>3</value>
        <value>4</value>
      </array>
    </array>
  </property>
</bean>
TestArrayBean
package com.chensan.spring.chapter4.test;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chensan.spring.chapter4.ArrayBean;

public class TestArrayBean {
	@Test
	public void testArrayInject() {
		BeanFactory beanFactory =  new ClassPathXmlApplicationContext("arrayBean.xml");
		ArrayBean beanImpl = beanFactory.getBean("arrayBean", ArrayBean.class);
		int arrLength = beanImpl.getArray().length;
		if(arrLength >0){
			for(int i = 0;i<arrLength;i++){
				System.out.println(beanImpl.getArray()[i]);
			}
		}
		
		int arrLength2 = beanImpl.getArray2().length;
		if(arrLength2 >0){
			for(int i = 0;i<arrLength2;i++){
				int arrLenth3 = beanImpl.getArray2()[i].length;
				for(int j=0;j<arrLenth3;j++){
					System.out.println(beanImpl.getArray2()[i][j]);
				}
			}
		}
	}
}

3.注入字典(Map)类型

MapBean

package com.chensan.spring.chapter4;

import java.util.Map;

public class MapBean {
	private Map<String, String> values;

	public Map<String, String> getValues() {
		return values;
	}

	public void setValues(Map<String, String> values) {
		this.values = values;
	}
	
}
mapBean.xml
<bean id="mapBean" class="com.chensan.spring.chapter4.MapBean">
  <property name="values">
    <map key-type="java.lang.String" value-type="java.lang.String">
      <entry>
	    <key>
	      <value>1</value>
	    </key>
	    <value>11</value>
      </entry>
      
      <entry key="2" value="22"/>
    </map>
  </property>
</bean>
TestMapBean
package com.chensan.spring.chapter4.test;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chensan.spring.chapter4.MapBean;

public class TestMapBean {
	@Test
	public void testSetInject() {
		BeanFactory beanFactory =  new ClassPathXmlApplicationContext("mapBean.xml");
		MapBean beanImpl = beanFactory.getBean("mapBean", MapBean.class);
		System.out.println(beanImpl.getValues());
		System.out.println(beanImpl.getValues().size());
	}
}
4.properties注入

PropertiesBean

package com.chensan.spring.chapter4;

import java.util.Properties;

public class PropertiesBean {
	private Properties values;

	public Properties getValues() {
		return values;
	}

	public void setValues(Properties values) {
		this.values = values;
	}
}
propertiesBean.xml
<bean id="propertiesBean" class="com.chensan.spring.chapter4.PropertiesBean">
  <property name="values">
    <props value-type="int" merge="default">
      <prop key="1">aaa</prop>
      <prop key="2">bbbbbb</prop>
    </props>
    
    <!-- 
     <value>
       1=11
       2=22
       3=33
       4=44
     </value>
     -->
  </property>
</bean>
TestPropertiesBean
package com.chensan.spring.chapter4.test;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chensan.spring.chapter4.PropertiesBean;

public class TestPropertiesBean {
	@Test
	public void testSetInject() {
		BeanFactory beanFactory =  new ClassPathXmlApplicationContext("propertiesBean.xml");
		PropertiesBean beanImpl = beanFactory.getBean("propertiesBean", PropertiesBean.class);
		System.out.println(beanImpl.getValues());
		System.out.println(beanImpl.getValues().size());
	}
}

5.引用其它Bean

BeanImpl2

package com.chensan.spring.chapter2;

import com.chensan.spring.chapter1.BeanApi;

public class BeanImpl2 implements BeanApi {
	private String message;

	public BeanImpl2(){
		this.message = "Hello Spring!";
	}

	public BeanImpl2(String message){
		this.message = message;
	}
	
	@Override
	public void sayHello() {
		System.out.println(message);
	}

	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}

BeanApiDecorator

package com.chensan.spring.chapter5;

import com.chensan.spring.chapter1.BeanApi;

public class BeanApiDecorator implements BeanApi {
	private BeanApi beanApi;
	
	public BeanApiDecorator() {
	}
	
	public BeanApiDecorator(BeanApi beanApi) {
		this.beanApi = beanApi;
	}

	public void setBeanApi(BeanApi beanApi) {
		this.beanApi = beanApi;
	}

	@Override
	public void sayHello() {
		beanApi.sayHello();
	}

}
bean5_1
<!-- 定义依赖Bean -->
<bean id="bean5_1_1" class="com.chensan.spring.chapter2.BeanImpl2"/>
<!-- 通过构造器注入 -->
<bean id="bean5_1_2" class="com.chensan.spring.chapter5.BeanApiDecorator">
  <constructor-arg index="0" ref="bean5_1_1"></constructor-arg>
</bean>
<!-- 通过构造器注入 -->
<bean id="bean5_1_3" class="com.chensan.spring.chapter5.BeanApiDecorator">
  <property name="beanApi">
    <ref bean="bean5_1_1"/>
  </property>
</bean>
TestDependencyInject
package com.chensan.spring.chapter5.test;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chensan.spring.chapter1.BeanApi;

public class TestDependencyInject {
	@Test
	public void testBeanInject(){
		BeanFactory beanFactory =  new ClassPathXmlApplicationContext("bean5_1.xml");
		//通过构造器方式注入
		BeanApi beanImpl1 = beanFactory.getBean("bean5_1_2", BeanApi.class);
		beanImpl1.sayHello();
		//通过setter方式注入
		BeanApi beanImpl2 = beanFactory.getBean("bean5_1_3", BeanApi.class);
		beanImpl2.sayHello();
	}
}

内容参考自:http://sishuok.com/forum/posts/list/2447.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值