6_Spring_Bean的自动装配

6_Spring_Bean的自动装配

bean自动装配

通过property标签可以手动指定给属性进行注入

我们也可以通过自动转配,完成属性的自动注入,就是自动装配,可以简化DI的配置

准备实体类

  1. package com.msb.bean;

  2. /**

    • @Author: Ma HaiYang
    • @Description: MircoMessage:Mark_7001
  3. */

  4. public class Dept {

  5. }

  6. package com.msb.bean;

  7. /**

    • @Author: Ma HaiYang
    • @Description: MircoMessage:Mark_7001
  8. */

  9. public class Emp {

  10. private Dept dept;

  11. @Override

  12. public String toString() {

  13. return "Emp{" +

  14. "dept=" + dept +

  15. '}';

  16. }

  17. public Dept getDept() {

  18. return dept;

  19. }

  20. public void setDept(Dept dept) {

  21. this.dept = dept;

  22. }

  23. public Emp() {

  24. }

  25. public Emp(Dept dept) {

  26. this.dept = dept;

  27. }

  28. }

配置文件

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:c="http://www.springframework.org/schema/c"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd">
  7. <!--
  8. autowire 属性控制自动将容器中的对象注入到当前对象的属性上
  9. byName 根据目标id值和属性值注入,要保证当前对象的属性值和目标对象的id值一致
  10. byType 根据类型注入,要保证相同类型的目标对象在容器中只有一个实例
  11. -->

测试代码

  1. package com.msb.test;
  2. import com.msb.bean.Emp;
  3. import com.msb.bean.User;
  4. import org.junit.Test;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6. /**
    • @Author: Ma HaiYang
    • @Description: MircoMessage:Mark_7001
  7. */
  8. public class Test2 {
  9. @Test
  10. public void testGetBean(){
  11. ClassPathXmlApplicationContext context =new
    ClassPathXmlApplicationContext("applicationContext2.xml");
  12. Emp emp = context.getBean("emp", Emp.class);
  13. System.out.println(emp);
  14. }
  15. }

Generated with Mybase Desktop 8.2.13

posted @ 2023-07-30 12:35  AidenDong  阅读(48)  评论(0)    收藏  举报