1.导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
2.实体类
package com.lobster.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 + '\'' +
'}';
}
}
3.bean文件
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用spring来创建对象,这些在spring中都称为bean-->
<bean id="hello" class="com.lobster.pojo.Hello">
<property name="str" value="HelloSpring"></property>
</bean>
</beans>
4.测试
import com.lobster.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
/*
我们的对象现在都在spring的容器里面了,要用就直接去里面取出来就可以
spring中所有的对象都叫做bean,现在我们要取出一个名字叫做hello的bean
然后把它强转为Hello类型
*/
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
![](https://img2020.cnblogs.com/blog/2096323/202008/2096323-20200827112608833-1658204150.png)