首先分析說明是構造器注入和setting注入
一、構造器注入
創建AccountServiceImpl繼承AccountService
import org.com.service.IAccountService;
import java.util.Date;
public class AccountServiceImpl implements AccountService {
private String name;
private Integer age;
private Date time;
public AccountServiceImpl(String name, Integer age, Date time) {
this.name = name;
this.age = age;
this.time = time;
}
public void saveAccount() {
System.out.println("service"+name+age+time);
}
}
配置xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountService" class="org.com.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="mys"></constructor-arg>
<constructor-arg name="age" value="21"></constructor-arg>
<constructor-arg name="time" ref="now"></constructor-arg>
</bean>
<bean id="now" class="java.util.Date"></bean>
</beans>
二、setting注入
創建Account類
import org.com.service.IAccountService;
import java.util.Date;
public class AccountServiceImpl {
private String name;
public void setName(String name){
this.name=name
}
public String getName){
return this.name;
}
}
配置xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="account" class="org.com.Account">
<property name="name" value="mxl"></property>
</bean>
</beans>
相比之下,setting注入具有如下的優點:
與傳統的JavaBean的寫法更相似,程序開發人員更容易理解、接受。通過setter方法設定依賴關係顯得更加直觀、自然。
對於複雜的依賴關係,如果採用構造注入,會導致構造器過於臃腫,難以閱讀。Spring在創建Bean實例時,需要同時實例化其依賴的全部實例,因而導致性能下降。而使用設值注入,則能避免這些問題。
尤其是在某些屬性可選的情況下,多參數的構造器更加笨重。