首先创建一个Person类
public class Person { private String name; public Person() { } public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "name=‘" + name + ‘\‘‘ + ‘}‘; } }
然后在resources目录下创建一个beans.xml文件
这是官网文档地址
https://docs.spring.io/spring-framework/docs/5.2.0.RELEASE/spring-framework-reference/index.html
beans.xml
<?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"> <bean id="Person" class="Person"> <property name="name" value="你好"/> </bean> </beans>
这个文件相当于执行了 Person person=new Person();
然后又执行了 person.setName="你好";
然后我们再创建一个MyTest测试类
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { @Test public void PersonTest() { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Object person = context.getBean("Person"); System.out.println(person); } }
测试结果
原文:https://www.cnblogs.com/Sum-muji/p/15127982.html