首先分析说明是构造器注入和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实例时,需要同时实例化其依赖的全部实例,因而导致性能下降。而使用设值注入,则能避免这些问题。
尤其是在某些属性可选的情况下,多参数的构造器更加笨重。