依賴注入的兩種形式
1.1構(gòu)造方法注入
LowerAction.class
public class LowerAction implements Action {
private String prefix;
private String message;
public LowerAction(){}
public LowerAction(String prefix, String message){
this.prefix = prefix;
this.message = message;
}
public String getPrefix() {
return prefix;
}
public String getMessage() {
return message;
}
public void setPrefix(String string) {
prefix = string;
}
public void setMessage(String string) {
message = string;
}
public void execute(String str) {
System.out.println((getPrefix() + ", " + getMessage() + ", " + str).toLowerCase());
}
}
ApplicationContext.xml中的TheAction2的Bean
<bean id="TheAction2" class="com.example.service.LowerAction">
<constructor-arg index="0">
<value>Hi</value>
</constructor-arg>
<constructor-arg index="1">
<value>Good Afternoon</value>
</constructor-arg>
</bean>
測(cè)試函數(shù)
@Test
public void test5() {
String XML = "file:src/applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(XML);
LowerAction lowerAction=(LowerAction) ctx.getBean("TheAction2");
System.out.println(lowerAction.getPrefix());
System.out.println(lowerAction.getMessage());
}
測(cè)試結(jié)果
測(cè)試結(jié)果
實(shí)驗(yàn)中想到的問(wèn)題:構(gòu)造注入只能通過(guò)index索引匹配嗎?
還有類型匹配
<bean id="TheAction4" class="com.example.service.LowerAction">
<constructor-arg type="java.lang.String">
<value>Hi</value>
</constructor-arg>
<constructor-arg type="java.lang.String">
<value>Wushuohan</value>
</constructor-arg>
</bean>
以及參數(shù)名傳值
<bean id="TheAction6" class="com.example.service.LowerAction">
<constructor-arg name="prefix" value="Hi">
</constructor-arg>
<constructor-arg type="message" value="Wushuohan">
</constructor-arg>
</bean>
測(cè)試結(jié)果如下
測(cè)試結(jié)果
Setter()方法注入
ApplicationContext.xml中的TheAction1的Bean
<bean id="TheAction1" class="com.example.service.LowerAction">
<property name="prefix">
<value>Hi</value>
</property>
<property name="message">
<value>Good Morning</value>
</property>
</bean>
測(cè)試函數(shù)
@Test
public void test4() {
String XML = "file:src/applicationContext.xml";
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(XML);
LowerAction lowerAction=(LowerAction) ctx.getBean("TheAction1");
System.out.println(lowerAction.getPrefix());
System.out.println(lowerAction.getMessage());
}
測(cè)試結(jié)果如下
測(cè)試結(jié)果
實(shí)驗(yàn)中想到的問(wèn)題:Setter()注入能不能沒(méi)有構(gòu)造函數(shù)?
注釋掉LowerAction的構(gòu)造函數(shù)
public class LowerAction implements Action {
private String prefix;
private String message;
public void execute(String str) {
System.out.println((getPrefix() + ", " + getMessage() + ", " + str).toLowerCase());
}
}
運(yùn)行后報(bào)錯(cuò)
報(bào)錯(cuò)
報(bào)錯(cuò)原因:TheAction2沒(méi)有構(gòu)造函數(shù)
TheAction2沒(méi)有了構(gòu)造函數(shù)
將這個(gè)Bean暫時(shí)刪除后紫新,運(yùn)行成功:
運(yùn)行成功
以上的測(cè)試說(shuō)明了Setter()注入可以沒(méi)有構(gòu)造函數(shù)漏峰,但是構(gòu)造注入必須有構(gòu)造函數(shù)。
本章總結(jié)
對(duì)于依賴關(guān)系無(wú)需變化的注入都办,盡量采用構(gòu)造注入。而其他的依賴關(guān)系的注入,則考慮采用設(shè)值注入度宦。