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

  1. beans标签是spring的专有标签,它的各个属性是固定的。
  2. bean标签的id是对象的名字,clsss是对象的类型。
  3. 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);    }}
  1. 当通过ClassPathXmlApplicationContext("beans.xml")获取beans的时候,就已经加载了beans中所有的bean(运行了所有的空参构造方法,get和set方法以及部分含参构造方法)。
  2. beans中的所有的bean只有一份,也就是说,运行两次context.getBean("helloSpring")方法获取到的两个对象是相同的。

运行结果:

在这里插入图片描述

上一篇:spring(4)——给beans中的bean对象取别名的两种方式,alias标签和bean的name属性
下一篇:visual studio——快速折叠所有代码和展开所有代码

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2025年03月31日 20时45分11秒