Spring:bean注入

网友投稿 205 2022-10-11


Spring:bean注入

目录Set 方法注入总结

Set 方法注入

1.新建一个空的 maven项目。

2.导入依赖

properties>

UTF-8

11

11

5.3.1

1.18.20

4.12

org.springframework

spring-beans

${spring.version}

org.springframework

spring-context

${spring.version}

org.projectlombok

lombok

${lombok.version}

junit

junit

${junit.version}

3.工程项目结构

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文件

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd">

1

1

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd">

1

1

写一个测试类

public class Test {

/**

* 通过 ClassPathXmlApplicationContext 获取 Spring 应用程序的 上下文 ApplicationContext

*/

@org.junit.Test

public 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.Test

public 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(…)

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注我们的更多内容!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:「全球数字经济大会」登陆 N 世界,融云提供通信云服务支持(世界数字经济和数字贸易大会)
下一篇:触摸屏如何利用无线PPI通信模块远程采集PLC数据?
相关文章

 发表评论

暂时没有评论,来抢沙发吧~