Spring的第一個例子,Spring第一個例子
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.輸出結果