spring实例入门

首先是bean文件:

package onlyfun.caterpillar;

public class HelloBean {
    private String helloWord = "";

    public void setHelloWord(String helloWord) {
        this.helloWord = helloWord;
    }

    public String getHelloWord() {
        return helloWord;
    }
}

 

再配置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.0.xsd">

    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
        <property name="helloWord" value="Hello!Justin!"></property>
    </bean>

</beans>

 

最后写测试代码:

package onlyfun.caterpillar;

import java.io.*;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class SpringTest {
    public static void main(String[] args) throws IOException {

        //BeanFactory方式读取bean

        //网上有用FileInputStream读bean.xml的例子,但似乎用的是老版本的spring
        Resource res = new ClassPathResource(
                "onlyfun/caterpillar/bean.xml");
        BeanFactory factory = new XmlBeanFactory(res);
        HelloBean hello = (HelloBean) factory.getBean("helloBean");
        System.out.println(hello.getHelloWord());

//         ApplicationContext方式读取bean

//         ApplicationContext application = new ClassPathXmlApplicationContext("onlyfun/caterpillar/bean.xml");
//         HelloBean hello = (HelloBean) application.getBean("helloBean");
//         System.out.println(hello.getHelloWord());
    }
}

 

要导入的包除了有spring的包外,还有commons-logging的包,在网上很容易下载。

本例中各包版本:

spring : spring-framework-2.5.6.SEC01

commons-logging : commons-logging-1.1.1

注意:本例中这3个文件在同一目录下

说 明:两者都是通过xml配置文件加载bean,ApplicationContext和BeanFacotry相比,提供了更多的扩展功能,但其主要区别 在于后者是延迟加载,如果Bean的某一个属性没有注入,BeanFacotry加载后,直至第一次使用调用getBean方法才会抛出异常;而 ApplicationContext则在初始化自身是检验,这样有利于检查所依赖属性是否注入;所以通常情况下我们选择使用 ApplicationContext.

参考:http://dinghaoliang.blog.163.com/blog/static/126540714201021234644910/

posted @ 2017-05-28 18:09  我是包子  阅读(762)  评论(0编辑  收藏  举报