构造器注入法:
/**
* 构造器注入可以根据参数索引注入、参数类型注入或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注解方式不能工作-->

本文详细介绍了Spring框架中构造器注入的三种方式:参数索引注入、参数类型注入及参数名称注入,并展示了如何通过不同方式配置Bean实现依赖注入。
208

被折叠的 条评论
为什么被折叠?



