
spring(2)——通过配置文件使用类,实现控制反转,实现不同的操作只需要在xml文件中进行修改
发布日期:2021-05-07 02:55:45
浏览次数:22
分类:精选文章
本文共 2300 字,大约阅读时间需要 7 分钟。
1.在maven中的pom.xml中导入spring依赖
org.springframework spring-webmvc 5.2.0.RELEASE
2.编写实体类
实体类一定要有get和set方法
package com.lixv.entity;public class Hello { private String str; public String getStr() { return str; } public void setStr(String str) { this.str = str; } @Override public String toString() { return "Hello{" + "str='" + str + '\'' + '}'; }}
package com.lixv.entity;public class HelloSpring { private String springStr; private Hello hello; public String getSpringStr() { return springStr; } public void setSpringStr(String springStr) { this.springStr = springStr; } public Hello getHello() { return hello; } public void setHello(Hello hello) { this.hello = hello; } @Override public String toString() { return "HelloSpring{" + "springStr='" + springStr + '\'' + ", hello=" + hello + '}'; }}
3.在resources中新增一个beans.xml文件
- beans标签是spring的专有标签,它的各个属性是固定的。
- bean标签的id是对象的名字,clsss是对象的类型。
- property标签的name属性是对象的属性名,value是赋值给这个属性的值,ref指向已经定义好的bean对象的id。
4.测试代码
package com.lixv.dao;import com.lixv.entity.Hello;import com.lixv.entity.HelloSpring;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestSpring { public static void main(String[] args) { //通过xml文件获取spring的beans,当获取spring的beans的时候,就已经将所有的bean加载出来了 ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //获取beans中的bean //beans中的所有的bean只有一份,也就是说,通过context.getBean("helloSpring")方法 HelloSpring hellospring = (HelloSpring) context.getBean("helloSpring"); HelloSpring hellospring2 = (HelloSpring) context.getBean("helloSpring"); System.out.println(hellospring); System.out.println(hellospring==hellospring2); }}
- 当通过
ClassPathXmlApplicationContext("beans.xml")
获取beans的时候,就已经加载了beans中所有的bean(运行了所有的空参构造方法,get和set方法以及部分含参构造方法)。 - beans中的所有的bean只有一份,也就是说,运行两次
context.getBean("helloSpring")
方法获取到的两个对象是相同的。
运行结果:

发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2025年03月31日 20时45分11秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
【故障公告】10:30-10:45 左右 docker swarm 集群节点问题引发故障
2021-05-09
工作半年的思考
2021-05-09
不可思议的纯 CSS 滚动进度条效果
2021-05-09
【CSS进阶】伪元素的妙用--单标签之美
2021-05-09
惊闻NBC在奥运后放弃使用Silverlight
2021-05-09
IE下尚未实现错误的原因
2021-05-09
创建自己的Docker基础镜像
2021-05-09
Python 简明教程 --- 20,Python 类中的属性与方法
2021-05-09
KNN 算法-理论篇-如何给电影进行分类
2021-05-09
Spring Cloud第九篇 | 分布式服务跟踪Sleuth
2021-05-09
CODING 敏捷实战系列课第三讲:可视化业务分析
2021-05-09
工作动态尽在掌握 - 使用 CODING 度量团队效能
2021-05-09
CODING DevOps 深度解析系列第二课报名倒计时!
2021-05-09
数据结构第八节(图(下))
2021-05-09
基于Mustache实现sql拼接
2021-05-09
POJ 2260 Error Correction 模拟 贪心 简单题
2021-05-09
gRPC在 ASP.NET Core 中应用学习(一)
2021-05-09
@SuppressWarnings 用法
2021-05-09
看完你就明白的锁系列之锁的状态
2021-05-09
看完这篇操作系统,和面试官扯皮就没问题了
2021-05-09