Spring核心之装配Bean--构造器注入
从上一节Spring的核心&入门我们发现,Spring默认会使用JavaBean的无参构造函数进行注入,其实Spring还提供了一种注入方式:构造器注入。
改变Spring配置文件spring-config.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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 注入hl(默认使用无参构造) -->
<bean id="hl" class="d20190124.HelloWorld">
<property name="name" value="nihao"></property>
</bean>
<!-- 使用Spring的构造方法 -->
<bean id="hl2" class="d20190124.HelloWorld">
<constructor-arg value="Spring"/>
</bean>
</beans>
如上所示:在<bean>
中使用<constructor-arg>
元素来告诉Spring额外的信息,但是我们直接这样写是会报错的:
通过IDEA的报错提示我们发现解决办法是要在HelloWorld.java
中创建一个带参构造函数,所以我们创建如下带参构造函数:
package d20190124;
public class HelloWorld {
private String name;
public HelloWorld(){
System.out.println("这是一个无参构造函数.");
}
public HelloWorld(String name){
this.name = name;
System.out.println("打印name的值:" + name);
System.out.println("这是一个带参构造函数.");
}
public void setName(String name) {
this.name = name;
}
public void sayHello(){
System.out.println("hello " + name);
}
}
结果:
综上
我们发现Spring会通过JavaBean的默认无参构造来实例化对象,并提供一种特殊的构造方法:构造器
来实例化Bean对象(但其实是使用了Bean对象的带参构造函数),构造器
的特点就是按需实例化
Spring支持实例化对象时提供额外的信息来覆盖本身定义的数据。
构造器另一种用法—>注入对象引用
spring-config.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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 注入hl(默认使用无参构造) -->
<bean id="hl" class="d20190124.HelloWorld">
<property name="name" value="nihao"></property>
</bean>
<!-- 使用Spring的构造方法 -->
<bean id="hl2" class="d20190124.HelloWorld">
<constructor-arg value="Spring"/>
</bean>
<bean id="hl3" class="d20190124.HelloWorld">
<constructor-arg value="123"/>
<constructor-arg ref="hl2"/>
</bean>
</beans>
在HelloWorld.java中添加:
public HelloWorld(int count, HelloWorld id){
this.name = id.viewHello();
System.out.println("打印count和name的值:" + count + "," + id.viewHello());
}
public String viewHello(){
return name;
}
结果:
总结
同上面的构造器注入方式我们发现,使用构造器注入,其实是使用JavaBean中的构造方法,而我们在构造器<constructor-arg>
中注入什么值,那么在Bean对象带参构造函数中的参数列表中就应该用什么值接收,比如我们,传入的是一个引用对象,那么就应该用对象最后接收参数。
Reference:https://tycoding.cn/2018/05/23/Spring-1/