依賴注入的兩種形式
1.1構造方法注入
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>
測試函數
@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());
}
測試結果
測試結果
實驗中想到的問題:構造注入只能通過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>
以及參數名傳值
<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>
測試結果如下
測試結果
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>
測試函數
@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());
}
測試結果如下
測試結果
實驗中想到的問題:Setter()注入能不能沒有構造函數?
注釋掉LowerAction的構造函數
public class LowerAction implements Action {
private String prefix;
private String message;
public void execute(String str) {
System.out.println((getPrefix() + ", " + getMessage() + ", " + str).toLowerCase());
}
}
運行后報錯
報錯
報錯原因:TheAction2沒有構造函數
TheAction2沒有了構造函數
將這個Bean暫時刪除后,運行成功:
運行成功
以上的測試說明了Setter()注入可以沒有構造函數,但是構造注入必須有構造函數。
本章總結
對于依賴關系無需變化的注入,盡量采用構造注入。而其他的依賴關系的注入,則考慮采用設值注入。