zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    jmeter学习笔记(3)-jmeter结合fiddler
    jmeter学习笔记(2)—http信息头管理器+断言
    requests接口自动化9-共享session和传递cookie
    djangorestframework学习1-通过HyperlinkedModelSerializer,ModelViewSet,routers编写第一个接口
    requests接口自动化8-传递数据为xml形式的post请求:data
    requests接口自动化7-Multi/form-data文件上传形式的post请求:files
    requests接口自动化6-Body里json格式数据形式的post请求:json
    requests接口自动化5-表单参数形式的post请求:data
    requests接口自动化4-登录后才能访问的get请求,需共享cookie
    requests接口自动化3-url里带参数的get请求:params
  • 原文地址:https://www.cnblogs.com/winstonet/p/6916265.html
Copyright © 2011-2022 走看看