package eneity; public class People { private String name; public People() { } public void sayHello() { System.out.println(this.getName() + "say : 'hello';"); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
在resources文件夾下建立spring的配置文件spring-config.xmljava
<?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容器中注入people對象--> <bean id="people" class="eneity.People"> <!--爲people對象注入屬性name:小張--> <property name="name" value="小張"/> </bean> </beans>
在java文件夾下建立Test文件夾並建立測試類TeatMainspring
public class TestMain { public static void main(String[] args) { //建立一個Spinrg的IOC容器對象 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringConfig.xml"); //獲取IOC容器中的people對象 People p = (People) applicationContext.getBean("people"); //執行people的sayHello()方法 p.sayHello(); } }
執行測試方法,看到控制檯輸出「小張say : 'hello';」app
這樣spring的小例子便完成了測試