1、编写实体类
public class Hello {
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
private String str;
}
2、写配置文件
<?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来创建对象-->
<bean id="hello" class="com.lin.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
<!--id=变量名 class=new 的对象 property 想当于给对象中的属性设置一个值!在这里想当于给str设置了spring的值-->
</beans>
输出结果:
3、测试
public class MyTest {
public static void main(String[] args) {
// 获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 我们要使用对象在context中取
Hello heo=(Hello)context.getBean("hello");
System.out.println(heo.toString());
}
}
对像由spring进行创建、管理。