Spring 入门 Ioc-Xml

通过一个小例子演视怎么通过 Spring 往程序中注入对象,而非手动 new 对象。

一、导入 Spring 所需要的包

spring-framework-2.5.6 版需要导入以下包:
1.-----  spring.jar
2.-----  commons-logging.jar

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的。

其他版本没有作测试。

 

二、添加一个测试用的实体类

User.java:

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;
    }

}

 

三、添加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。

<property name="name" value="hahahaha"/> 告诉Spring 创建User对象时为该对象的name属性值为"hahahaha"。

四、测试,通过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" 。

另外,在Spring 3.2.4 中会报Resource leak: 'appctx' is never closed 警告,eclipse 建议我们要关闭 ClassPathXmlApplicationContext 。在最后添加如下代码:

((ClassPathXmlApplicationContext)appctx).close();

完工。。。

原文地址:https://www.cnblogs.com/likailan/p/3446821.html