Spring 入門 Ioc-Xml

經過一個小例子演視怎麼經過 Spring 往程序中注入對象,而非手動 new 對象。java

1、導入 Spring 所須要的包

spring-framework-2.5.6 版須要導入如下包:
1.-----  spring.jar
2.-----  commons-logging.jarspring

spring-framework-3.2.4 版須要導入如下包:
1.-----  spring-core-3.2.4.RELEASE.jar
2.-----  spring-beans-3.2.4.RELEASE.jar
3.-----  spring-context-3.2.4.RELEASE.jar
4.-----  spring-expression-3.2.4.RELEASE.jar
5.-----  commons-logging.jar
但貌似 spring-framework-3.2.4 裏並無 commons-logging.jar包,能夠使用spring-framework-2.5.6的或者使用Struts2的。express

其餘版本沒有做測試。app

 

2、添加一個測試用的實體類

User.java:eclipse

public class User {
    private int id;
    private String name;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

 

3、添加Spring配置文件

在src目錄下添加 applicationContext.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
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">


    <bean id="user" class="com.startspring.User">
        <property name="name" value="hahahaha"/>
    </bean>
    
</beans>

<bean id="user" class="com.startspring.User"> 爲 com.startspring.User 類取了個id名爲 user。this

<property name="name" value="hahahaha"/> 告訴Spring 建立User對象時爲該對象的name屬性值爲"hahahaha"。spa

 

4、測試,經過Spring注入獲得對象

public class Start {
    public static void main(String[] args) {
        //把Spring配置文件名"applicationContext.xml"傳進去。
        ApplicationContext appctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //獲得id爲user對應類的對象
        User u = (User)appctx.getBean("user");
        System.out.println(u.getName());
        
    }
}

能夠看到,代碼中並無 new User對象,對象的建立都是由Srping完成,併爲User對象的name屬性賦值爲 "hahahaha" 。code

另外,在Spring 3.2.4 中會報Resource leak: 'appctx' is never closed 警告,eclipse 建議咱們要關閉 ClassPathXmlApplicationContext 。在最後添加以下代碼:xml

((ClassPathXmlApplicationContext)appctx).close();

 

完工。。。

相關文章
相關標籤/搜索