Spring:bean注入--Set方法注入

目录

  • Set 方法注入
  • 总结

Set 方法注入 1.新建一个空的 maven项目。
2.导入依赖
properties>UTF-811115.3.11.18.204.12org.springframeworkspring-beans${spring.version}org.springframeworkspring-context${spring.version}org.projectlomboklombok${lombok.version}junitjunit${junit.version}

3.工程项目结构
Spring:bean注入--Set方法注入
文章图片

4.新建包 com.crush.pojo
5.新建Java类Student
@Data // set、get 方法@AllArgsConstructor // 全参构造@NoArgsConstructor// 无参构造public class Student {/*** 学号*/private Long number; /*** 学生姓名*/private String name; /*** 所在学校*/private String school; }

resource 下 beans.xml文件
11

写一个测试类
public class Test {/*** 通过 ClassPathXmlApplicationContext 获取 Spring 应用程序的 上下文 ApplicationContext*/@org.junit.Testpublic void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); // 第一种方式 获取ioc 容器中的Student 强制类型转换Student student = (Student) applicationContext.getBean("student"); // 第二种方式 直接在后面写明类的标签。Student student1 = applicationContext.getBean("student", Student.class); // student.setName("cccc"); 给其中一个修改 就会全部修改 可以自己打开测试下 System.out.println(student); System.out.println(student1); // 这里结果为true // 解释:因为Spring 默认构造出来的对象 默认是单例的。 无论获取多少次 ,都是单例的。System.out.println(student==student1); }/*** 通过 FileSystemXmlApplicationContext 获取 Spring 应用程序的 上下文 ApplicationContext* 还有第三种是 通过Web服务器实例化 ApplicationContext 容器*/@org.junit.Testpublic void test2(){//这里的路径 也可以 用绝对路径ApplicationContext applicationContext = new FileSystemXmlApplicationContext("src\\main\\resources\\beans.xml"); Student student = applicationContext.getBean("student", Student.class); System.out.println(student); }}

小小思考
为什么 new ClassPathXmlApplicationContext(“beans.xml”); 要用ApplicationContext 来接收,而不用ClassPathXmlApplicationContext 接收呢?
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

解释:
按照面向接口编程的思想,声明变量应该是接口类型的,然后创建一个该接口的实现类的实例赋值给该变量。 ApplicationContext是接口,ClassPathXmlApplicationContext是它的一个实现类。所以你就看到了 ApplicationContext ac = new ClassPathXmlApplicationContext(…)

总结 【Spring:bean注入--Set方法注入】本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

    推荐阅读