<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency>

package com.xiaofu.pojo; 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 + ‘\‘‘ + ‘}‘; } }

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--使用spring来创建对象,在spring这些都称为bean--> <!--一个bean就相当于一个对象--> <!--property 相当于给属性设置值 name 类的属性名 value 给属性设置的值--> <bean id="hello" class="com.xiaofu.pojo.Hello"> <property name="str" value="Spring"/> </bean> </beans>
现在刚刚创建的类 就已经被spring管理了

 新建一个测试类来使用一下spring的容器:
代码:
import com.xiaofu.pojo.Hello; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Text { public static void main(String[] args) { //获取spring的上下文对象 ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //我们的对象现在都在spring容器中管理了,我们要使用,直接去里面取出来就可以了! Hello hello = (Hello) context.getBean("hello"); //这的hello 对应的就是beans.xml文件中的bean标签的id System.out.println(hello.toString()); } }
运行一下:
可以看到 并没有 new一个Hello对象 我们设置和拿到的类的属性
原文:https://www.cnblogs.com/love2000/p/14235012.html