DI之構造器注入
通過構造器的參數進行注入,Spring提供三種方式來匹配參數。
在<bean>的<constructor-arg>中,有下列三個屬性。
name:通過參數名。
type:通過參數類型。
index:通過參數位置。(0開始)
即使在配置文件中,所配置的參數標籤和構造器參數位置不一致,
Spring也能自動選擇最匹配的構造方法。
但是在配置文件中所配置的參數,必須存在對應的構造方法以供注入,
即:用於注入的構造方法中的參數,在配置文件中必須進行配置。
其餘的配置細節與Setter類似。
· 配置演示
BeanObject
@ToString
public class BeanObject implements IBeanObject {
/* 簡單值 */
private long sn;
private String name;
/* 依賴的bean對象 */
private IOtherBean other;
/* 集合 */
private List list;
/* Properties對象*/
private Properties properties;
public BeanObject(long sn, String name, IOtherBean other, List list,
Properties properties) {
this.sn = sn;
this.name = name;
this.other = other;
this.list = list;
this.properties = properties;
}
public BeanObject(){
System.out.println("new BeanObject");
}
}
配置文件
<bean id="otherBean" name="other" class="com.hanaii.di.constructor.OtherBean"/>
<bean id="beanObject" class="com.hanaii.di.constructor.BeanObject">
<!-- 使用參數名字匹配 -->
<constructor-arg name="name" value="hanaii"/>
<!-- 使用參數類型匹配 -->
<constructor-arg type="long" value="1"/>
<!-- 使用參數索引匹配 -- >
<constructor-arg index="2" ref="otherBean"/>
<!-- 具體的配置和setter注入類似 -->
<constructor-arg name="properties">
<props >
<prop key="system_langunge">簡體中文</prop>
</props>
</constructor-arg>
<constructor-arg name="list" >
<list>
<value>1</value>
</list>
</constructor-arg>
</bean>
</beans>
配置文件中參數順序和構造方法不一致,也沒關係,Spring會自動匹配。
測試代碼
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ConstructorTest {
@Autowired
ApplicationContext ctx;
@Test
public void test1(){
BeanObject obj = ctx.getBean("beanObject", BeanObject.class);
System.out.println(obj);
}
}
測試結果
BeanObject(sn=1, name=hanaii,
other=com.hanaii.di.constructor.OtherBean@69b794e2,
list=[1], properties={system_langunge=簡體中文})