package bean.ditest;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DiTest {
@Test
public void test(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans-diTest.xml");
Dept dept1 = (Dept) ac.getBean("dept1");
dept1.info();
System.out.println(dept1);
Emp emp1 = (Emp) ac.getBean("emp1");
emp1.work();
System.out.println(emp1);
}
}
?
<?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="dept1" class="bean.ditest.Dept">
<property name="dname" value="安保部门"></property>
</bean>
<bean id="emp1" class="bean.ditest.Emp">
<!-- 注入对象属性-->
<property name="age" value="21"></property>
<!-- 注入普通数据属性-->
<property name="ename" value="吴危险"></property>
<property name="dept" ref="dept1"></property>
</bean>
</beans>
package bean.ditest;
public class Emp {
private Dept dept;
private String ename;
private String age;
public void work(){
System.out.println(ename+"工作中"+",年龄:"+age);
dept.info();
}
@Override
public String toString() {
return "Emp{" +
"dept=" + dept +
", ename='" + ename + '\'' +
", age='" + age + '\'' +
'}';
}
public Emp() {
}
public Emp(Dept dept, String ename, String age) {
this.dept = dept;
this.ename = ename;
this.age = age;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
package bean.ditest;
public class Dept {
private String dname;
public void info(){
System.out.println("部门名称:"+dname);
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public Dept(String dname) {
this.dname = dname;
}
public Dept() {
}
@Override
public String toString() {
return "Dept{" +
"dname='" + dname + '\'' +
'}';
}
}