`

跟我学Spring3 学习笔记三

 
阅读更多

     构造器注入法:

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

	private String message;
	private int index;
	@ConstructorProperties({"message","index"})
	public HelloImplConstr(String message,int index){
		this.message = message;
		this.index = index;
	}
	public void sayHello() {
		System.out.println(this.index+":"+this.message);

	}
}

 

<!-- 通过构造器参数索引方式依赖注入 -->
<bean id="byIndex" class="com.constructor.HelloImplConstr">
    <constructor-arg index="0" value="Hello Spring by index"></constructor-arg>
    <constructor-arg index="1" value="1"></constructor-arg>
</bean>
<!-- 通过构造器参数类型方式依赖注入 -->  
<bean id="byType" class="com.constructor.HelloImplConstr">
   <constructor-arg type="java.lang.String" value="Hello Spring by type"></constructor-arg>
   <constructor-arg type="int" value="2"></constructor-arg>
</bean>
<!-- 通过构造器参数名称方式依赖注入 -->  
<bean id="byName" class="com.constructor.HelloImplConstr">
     <constructor-arg name="message" value="Hello Spring by name"></constructor-arg>
     <constructor-arg name="index" value="3"></constructor-arg>
</bean>
<!-- 静态工厂方法注入和实例工厂注入 参数注入一样 静态工厂方式和实例工厂方式根据参数名字注入的方式
只支持通过在class文件中添加“变量调试信息”方式才能运行,ConstructorProperties注解方式不能工作-->

 

 

分享到:
评论
1 楼 sblig 2012-07-12  

@Test 
	public void testConstructor(){
		//读取配置文件实例化一个Ioc容器
		ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml");
		//构造器注入 根据参数索引进行注入
		HelloApi helloApi = context.getBean("byIndex",HelloApi.class);
		helloApi.sayHello();
		
		//构造器注入 根据参数类型进行注入
		HelloApi helloApi2 = context.getBean("byType",HelloApi.class);
		helloApi2.sayHello();
		
		//构造器注入 根据参数名字进行注入
		HelloApi helloApi3 = context.getBean("byName",HelloApi.class);
		helloApi3.sayHello();
		
	}
 

相关推荐

Global site tag (gtag.js) - Google Analytics