Spring 的控制翻轉IoC,或者依賴注入。在測試類中沒有new一個新對象,對象是從xml文件中注入的。
xml文件中的<beans>是一個大容器,裡面的<bean>就是容器裡面的內容,這些內容是一個一個的實例對象。
我們把對象創建在了xml文件中,所以就不用再在Java中創建對象了,當我們使用這些對象的時候,就從xml的bean注入即可。
1.創建類
package com.wangcf;
public class HelloWorld {
private String name;
public void sayHello(){
System.out.println("Hello World"+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.創建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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
>
<!-- 注冊一個Hello World,實例名稱為HelloWorld -->
<bean name="helloworld" class="com.wangcf.HelloWorld">
<property name="name">
<value>小明</value>
</property>
</bean>
</beans>
3.創建測試類
package com.wangcf;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloTest {
@Test
public void testSayHello() {
//創建Spring 容器
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
//從容器中得到一個bean,也就是一個實例對象
HelloWorld hello=(HelloWorld)context.getBean("helloworld");
hello.sayHello();
}
}
4.輸出結果
