0
点赞
收藏
分享

微信扫一扫

Spring基于XML的DI之构造注入

茗越 2022-06-24 阅读 76

Spring基于XML的DI之构造注入


构造注入

构造注入是指,在构造 调用者实例化的同时,完成被调用者的实例的初始化,即:使用构造器设置依赖关系。

举个栗子

Studnet.java

package com.hk.spring.di02;

public class Student {

private String name;
private int age;
private School school;//域属性

public Student() {
System.out.println("无参构造器被执行");
}

public Student(String name, int age, School school) {
this.name = name;
this.age = age;
this.school = school;
}
public void setSchool(School school) {
this.school = school;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", school=" + school
+ "]";
}


}


School.java

package com.hk.spring.di02;

public class School {

private String schloolName;

public void setSchloolName(String schloolName) {
this.schloolName = schloolName;
}

@Override
public String toString() {
return "School [schloolName=" + schloolName + "]";
}

}


applicationContext.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">
<!-- 学校依旧使用设置注入 -->
<bean id="mySchool" class="com.hk.spring.di02.School">
<property name="schloolName" value="红林小学"/>
</bean>
<bean id="myStudent" class="com.hk.spring.di02.Student">
<!-- 构造注入 下标从0开始,顺序与构造方法参数顺序一致-->
<constructor-arg index="0" value="小明"/>
<constructor-arg index="1" value="9"/>
<!-- 域属性 ref="mySchool"-->
<constructor-arg index="2" ref="mySchool"/>
</bean>
</beans>


又是似曾相识的index,这玩意先别说不一定知道从0还是1开始,光是顺序就要搞死人,所以一般用name属性

applicationContext.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">
<!-- 学校依旧使用设置注入 -->
<bean id="mySchool" class="com.hk.spring.di02.School">
<property name="schloolName" value="红林小学"/>
</bean>
<bean id="myStudent" class="com.hk.spring.di02.Student">
<!-- 构造注入-->
<constructor-arg name="name" value="小明"/>
<constructor-arg name="age" value="9"/>
<!-- 域属性 ref="mySchool"-->
<constructor-arg name="school" ref="mySchool"/>
</bean>
</beans>


测试类

package com.hk.spring.di02;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest {
@Test
public void test1(){
String resource = "com/hk/spring/di02/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
Student stu = (Student) ac.getBean("myStudent");
System.out.println(stu);

}
}


结果

Student [name=小明, age=9, school=School [schloolName=红林小学]]


可能你已经发现了,无参构造器并没有执行,其实构造注入不需

要无参构造器,但是无参构造器还是需要的,别的地方可能会使用


举报

相关推荐

0 条评论