使用构造器注入通过配置构造器参数实现,构造器参数就是依赖
1:按照参数索引依赖注入的Bean
2:按照参数类型依赖注入的Bean
3:根据参数名称依赖注入的Bean
package org.spring.chapter2.helloworld;
public class HelloImpl3 implements HelloApi {
private String message;
private int index;
public HelloImpl3() {
this.message="Hello World in Empty Constructor";
}
public HelloImpl3(String message,int index) {
this.message = message;
this.index = index;
}
@Override
public void sayHello() {
System.out.println(index+":"+message);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 通过构造器参数索引方式依赖注入 -->
<bean id="byIndex" class="org.spring.chapter2.helloworld.HelloImpl3">
<constructor-arg index="0" value="Hello Spring By Index" />
<constructor-arg index="1" value="1"></constructor-arg>
</bean>
<!-- 通过构造器参数类型方式依赖注入 -->
<bean id="byType" class="org.spring.chapter2.helloworld.HelloImpl3">
<constructor-arg type="java.lang.String" value="Hello Spring By Type" />
<constructor-arg type="int" value="2" />
</bean>
<!-- 通过构造器参数名称方式依赖注入 -->
<bean id="byName" class="org.spring.chapter2.helloworld.HelloImpl3">
<constructor-arg name="message" value="Hello Spring By Name" />
<constructor-arg name="index" value="3"/>
</bean>
</beans>
@Test
public void testConstructInject(){
ApplicationContext context = new ClassPathXmlApplicationContext("org/spring/chapter2/helloworld/helloworld5.xml");
//1:按照参数索引依赖注入的Bean
HelloApi byIndex = context.getBean("byIndex",HelloApi.class);
byIndex.sayHello();
//2:按照参数类型依赖注入的Bean
HelloApi byType = context.getBean("byType",HelloApi.class);
byType.sayHello();
//3:根据参数名称依赖注入的Bean
HelloApi byName = context.getBean("byName",HelloApi.class);
byName.sayHello();
}