spring6 依赖注入-对象属性类型
2023-12-15 12:37:39
DiTest.java
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);
}
}
?
beans-diTest.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="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>
?两个实体类:
Emp.java
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;
}
}
Dept.java
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 + '\'' +
'}';
}
}
?控制台输出:
总结:
文章来源:https://blog.csdn.net/qq_64005599/article/details/135014075
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!