spring6 依赖注入-对象属性类型

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 




    


    

        

        
        
    

 两个实体类:

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 + '\'' +
                '}';
    }
}

 控制台输出:spring6 依赖注入-对象属性类型_第1张图片

总结:

spring6 依赖注入-对象属性类型_第2张图片

你可能感兴趣的:(Javaee,java,开发语言)