1.项目创建
https://blog.csdn.net/zhaolinxuan1/article/details/84897949
https://blog.csdn.net/zhaolinxuan1/article/details/84932897
2.UserInfo类
public class UserInfo {
private String name;
private Integer age;
private DepartMent departMent;
public UserInfo(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public DepartMent getDepartMent() {
return departMent;
}
public void setDepartMent(DepartMent departMent) {
this.departMent = departMent;
}
@Override
public String toString() {
return "UserInfo [name=" + name + ", age=" + age + ", departMent=" + departMent + "]";
}
}
DepartMent类:
public class DepartMent {
private Integer deId;
private String deName;
public Integer getDeId() {
return deId;
}
public DepartMent(){}
public void setDeId(Integer deId) {
this.deId = deId;
}
public String getDeName() {
return deName;
}
public void setDeName(String deName) {
this.deName = deName;
}
@Override
public String toString() {
return "DepartMent [deId=" + deId + ", deName=" + deName + "]";
}
}
3.beans.xml
在xml中创建
<bean id="departMent" class="com.DepartMent">
<property name="deId" value="101"/>
<property name="deName" value="技术部"/>
</bean>
使用<property name="departMent" ref="departMent"/> 注入userInfo 的bean中
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean id="departMent" class="com.DepartMent">
<property name="deId" value="101"/>
<property name="deName" value="技术部"/>
</bean>
<!-- 依赖注入 -->
<bean id="userInfo" class="com.UserInfo" scope="singleton">
<property name="name" value="zlx"/>
<property name="age" value="29"/>
<property name="departMent" ref="departMent"/>
</bean>
</beans>
4.测试
public class Test {
public static void main(String[] args) {
ConfigurableApplicationContext bf = new ClassPathXmlApplicationContext("beans.xml");
UserInfo userInfo = (UserInfo) bf.getBean("userInfo");
System.out.println(userInfo);
}
}