zoukankan      html  css  js  c++  java
  • Spring XmlBeanFactory例子[转]

    // Car.java

    package com.baobaotao.beanfactory;

    public class Car {
        private String brand;
        private String color;
        private int maxSpeed;

        public Car() {
        }

        public void introduce() {
            System.out.println("brand:" + brand + "; color:" + color + "; maxSpeed:"
                    + maxSpeed);
        }

        public String getBrand() {
            return brand;
        }

        public void setBrand(String brand) {
            this.brand = brand;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }

        public int getMaxSpeed() {
            return maxSpeed;
        }

        public void setMaxSpeed(int maxSpeed) {
            this.maxSpeed = maxSpeed;
        }
    }
    // beans.xml

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
     "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
     
    <beans>
        <bean id="car" class="com.baobaotao.beanfactory.Car">
            <property name="brand" value="红旗CA72"></property>
            <property name="color" value="黑色"></property>
            <property name="maxSpeed" value="200"></property>
        </bean>
    </beans>

    // BeanFactoryTest.java

    package com.baobaotao.beanfactory;

    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 BeanFactoryTest {
        public static void main(String[] args) throws Throwable {
            Resource res = new ClassPathResource(
                    "com/baobaotao/beanfactory/beans.xml");
            BeanFactory bf = new XmlBeanFactory(res);
            Car car = (Car) bf.getBean("car");
            car.introduce();
        }
    }

        Spring用Resource接口表示一个来源无关的资源。这里,我们使用Resource表示Spring配置文件。XmlBeanFactory通过Resource装载Spring配置信息并启动IoC容器,然后就可以能过BeanFactory#getBean(beanName)方法从IoC容器中获取Bean了。通过BeanFactory启动IoC容器时,并不会初始化配置文件中定义的Bean,初始化动作发生在第一个调用时。对于单实例(singleton)的Bean来说,BeanFactory会缓存Bean实例,所以第二次使用getBean()获取Bean时将直接从IoC容器的缓存中获取Bean实例。

  • 相关阅读:
    df值自由度学习[转载]
    调用sklearn包中的PLA算法[转载]
    箱线图+小提琴图学习[转载]
    P1616 疯狂的采药 洛谷
    P1164 小A点菜 洛谷
    【noip模拟赛3】确定的位置 (map的遍历 位置原理)
    【noip模拟赛1】古韵之鹊桥相会(最短路)
    【noip模拟赛3】贾老二的工件 (模拟)
    【noip模拟赛1】古韵之乞巧 (dp)
    【noip模拟赛3】拣钱
  • 原文地址:https://www.cnblogs.com/yqskj/p/2964181.html
Copyright © 2011-2022 走看看