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/

  • 相关阅读:
    前台的js对象数组传到后台处理。在前台把js对象数组转化为json字符串,在后台把json字符串解析为List<>
    ef中用lambda expressions时要注意(m=>m.id ==b ) 此时的b只能是基本的数据类型 。连属性都不能用
    你是否有遇到过某个实体类字段(属性)过多的情况,不想每次点的话戳进来(C# 反射)
    razor使用注意点........
    让简历在15秒内吸引招聘者《我的前程我做主》六
    JavaScript学习总结(十六)——Javascript闭包(Closure)
    C#操作XML的完整例子——XmlDocument篇(转载,仅做学习之用)
    C#操作XML方法集合
    图片超链接作为下载来处理
    架构师手记
  • 原文地址:https://www.cnblogs.com/winstonet/p/6916265.html
Copyright © 2011-2022 走看看