您的位置:首页 > 其它

三种不同方式的构造器注入

2013-04-02 14:51 633 查看
1 java类

public class HelloImpl implements IHello {
private String message;
private int index;

public HelloImpl(String message, int index) {
this.message = message;
this.index = index;
}

public HelloImpl(){}

@Override
public void sayHello() {
System.out.println(this.index + ":" + message);
}
}


2 配置文件init_bean.xml

<!--通过构造器参数索引方式依赖注入  -->
<bean id="byIndex"  class="com.pyy.HelloImpl">
<constructor-arg index="0" value="Hello Spring"/>
<constructor-arg index="1" value="1"/>
</bean>
<!--通过构造器参数类型方式依赖注入  -->
<bean id="byType"  class="com.pyy.HelloImpl">
<constructor-arg type="java.lang.String" value="Hello Spring"/>
<constructor-arg type="int" value="2"/>
</bean>
<!--通过构造器参数名字方式依赖注入  -->
<bean id="byName"  class="com.pyy.HelloImpl">
<constructor-arg name="message"  value="Hello Spring"/>
<constructor-arg name="index" value="3"/>
</bean>


3测试代码

@Test
public void testConstruct(){
ApplicationContext beans = new ClassPathXmlApplicationContext(
"/config/init_bean.xml");
HelloImpl bean1 = beans.getBean("byIndex", HelloImpl.class);
bean1.sayHello();
HelloImpl bean2 = beans.getBean("byType", HelloImpl.class);
bean2.sayHello();
HelloImpl bean3 = beans.getBean("byName", HelloImpl.class);
bean3.sayHello();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: