天天看點

學習Spring的第一個HelloWorld

1 配置Spring

建立一個java工程,導入如下包:

學習Spring的第一個HelloWorld

2 開始Spring程式設計

1 建立一個HelloWorld.java

package test;
public class HelloWorld {
    private String info ;
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }

}
           

2 編寫配置檔案applicationContext.xml

在目前工程下建立一個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: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">    
    <!-- 配置需要被Spring管理的Bean(建立,建立後放在了Spring IOC容器裡面)-->  
    <bean id="hello" class="test.HelloWorld">  
        <!-- 配置該Bean需要注入的屬性(是通過屬性set方法來注入的) -->  
        <property name="info" value="Hello World!"/>  
    </bean>  
</beans>  
           

3 反轉控制開始

在Main.java中添加如下:

package test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
    public static void main(String[] args) {
        //擷取Spring的ApplicationContext配置檔案,注入IOC容器中  
        //(Map: key:String, bean标簽的id屬性值 ==>value:Object, bean标簽class屬性所指類的執行個體)  
        BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
        /*
        HelloWorld hw1 = new HelloWorld();
        hw1.setInfo("Hello World!");
        */
        //Spring相當于如上代碼,通過getBean擷取xml檔案中對應id值的Bean,在xml檔案中配置該Bean需要注入的屬性
        //不需要自己new對象以及指派.
        HelloWorld hw1 = (HelloWorld)factory.getBean("hello");//map.get("hello")  
        System.out.println(hw1.getInfo());  
        System.out.println(hw1);  
    }
}
           

3 測試結果

學習Spring的第一個HelloWorld

3 總結

Spring可以通過配置的方法取得對象,而不再用new的方法來取得對象

* 先在xml配置檔案中配置bean标簽,如:

<bean id="hello" class="test.HelloWorld">  
        <!-- 配置該Bean需要注入的屬性(是通過屬性set方法來注入的) -->  
        <property name="info" value="Hello World!"/>  
    </bean>  
           

其中

id 為bean的key,通過之後getBean()取得配置的Bean.

class 為建立的類所在包+類名

property标簽為該Bean配置注入的屬性.

  • 反轉控制

1 通過

BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
           

來擷取配置檔案

2 通過getBean擷取xml檔案中對應id值的Bean,就可以取得我們想要得到的對象了.

學習自:http://blog.csdn.net/evankaka