Spring依赖注入的实现方式
在Spring中,有两种实现依赖注入的方式:
- 属性setter方法注入
- 构造方法注入
第一种,通过setter方法
注意:使用该方法时,bean类种需要为该类的成员变量设置set方法
bean类
public class Teacher implements User {
private String jobNum;
private String name;
private int age;
private String phoneNum;
public String getJobNum() {
return jobNum;
}
public void setJobNum(String jobNum) {
this.jobNum = jobNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
@Override
public String toString() {
return "Teacher{" +
"jobNum='" + jobNum + '\'' +
", name='" + name + '\'' +
", age=" + age +
", phoneNum='" + phoneNum + '\'' +
'}';
}
在配置文件当中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="Teacher" class="com.gk.homework.pojo.Teacher">
<property name="age" value="40"></property>
<property name="jobNum" value="2018131905"></property>
<property name="name" value="Joe"></property>
<property name="phoneNum" value="16817328033"></property>
</bean>
</beans>
测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class TestTeacher {
@Autowired
Teacher teacher;
@Test
public void testToString(){
System.out.print(teacher.toString());
}
}
测试结果:
第二种,通过构造方法
注意:在bean类中需要设置该类有参数的构造方法
bean类:
Teacher(String name,int age,String jobNum,String phoneNum){
this.name = name;
this.age = age;
this.jobNum = jobNum;
this.phoneNum = phoneNum;
}
(这里只补充bean类的关键代码)
在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="Teacher" class="com.gk.homework.pojo.Teacher">
<constructor-arg name="name" value="Mike"></constructor-arg>
<constructor-arg name="age" value="55"/>
<constructor-arg name="jobNum" value="2018131905"/>
<constructor-arg name="phoneNum" value="13928430321"/>
</bean>
</beans>
test类与上文相同。
本文由博客群发一文多发等运营工具平台 OpenWrite 发布