zoukankan      html  css  js  c++  java
  • 2015年11月30日 spring初级知识讲解(一)装配Bean

    序,Spring的依赖注入是学习spring的基础。IOC为控制反转,意思是需要的时候就由spring生成一个,而不是先生成再使用。

    写在前面

    Spring提供面向接口编程,面向接口编程与依赖注入协作实现了松散耦合。

    Spring.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" xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
           http://www.springframework.org/schema/context ">
           <!-- Beans 声明 -->
    </beans>

    从Spring获得Bean

    package single.spring;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class testSpringXML {
    
        public static void main(String[] args) throws PerformanceException {
            //装配Spring.xml配置文件
            ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
            //从Spring容器获得声明的Bean
            Performer performer = (Performer) ctx.getBean("duke");
            //执行Bean的方法
            performer.perform();
        }
    }

    一、默认构造函数注入

    要求此类具有默认构造函数

    <bean id="duke" class="single.spring.Juggler"></bean>

    二、通过构造器注入

    1 含参构造函数,参数为基本数据类型

    public Juggler(int beanBags) {
      this.beanBags = beanBags;
    }

    使用传参构造函数实例化Bean

    <bean id="duke" 
                class="single.spring.Juggler">
        <!-- 通過含參構造函數實例化Bean -->
        <constructor-arg value="15"></constructor-arg>
        </bean>

    2 含参数构造函数,参数为引用类型

    Performer poeticDuke = (Performer)ctx.getBean("poeticDuke");
    poeticDuke.perform();

    <bean id="poeticDuke" class="single.spring.PoeticJuggler">
            <constructor-arg value="15"></constructor-arg>
            <!-- 参数类型为引用类型 用ref-->
            <constructor-arg ref="sonnet29"></constructor-arg>
        </bean>
    
        <bean id="sonnet29" class="single.spring.Sonnet29">
        </bean>

    三、通过工厂方法创建Bean

    有时候静态工厂方法是实例化对象的唯一方法,出于线程安全考虑,getInstance()使用了一种被称为“initialization on demand holder”的技术来创建单例类的实例。

    Initialization on Demand Holder模式,这种方法使用内部类来做到延迟加载对象,在初始化这个内部类的时候,JLS(Java Language Sepcification)会保证这个类的线程安全(the class initialization phase is guaranteed by the JLS to be serial),这种写法最大的美在于,完全使用了Java虚拟机的机制进行同步保证,没有一个同步的关键字。

    package single.spring;
    
    public class Stage {
        private Stage() {
        }
    
        //延迟加载实例
        private static class StageSingletonHolder {
            static Stage instance = new Stage();
        }
        //返时实例
        public static Stage getInstance() {
            return StageSingletonHolder.instance;
        }
    }

    spring.xml配置,factory-method属性配置静态方法

    <bean id="theStage" class="single.spring.Stage" factory-method="getInstance"></bean>

    四、Bean的作用域

    所有的Spring Bean默认都是单例,但是Spring提供了一个scope属性来每次成不同的实例

    singleton:在每个Spring容器中,一个Bean定义只有一个对象实例(默认)

    prototype:允许Bean的定义可以被实例化任意次(每次调用都创建一个实例)

    request:在一次Http请求中,每个Bean定义对应一个实例,该作用域仅在基于Web的Spring的上下文(例如Spring MVC)中才有效。

    session:在一个Http Session中,每个Bean定义对应一个实例。该作用域仅在基于Web的Spring上下文(例如Spring MVC)中才有效。

    global-session:在一个全局Http Session中,每个Bean定义对应一个实例。该作用域仅在Portlet上下文中才有效。

    五、初始化和销毁Bean

    为了满足初始化和销毁Bean的需求,Spring提供了Bean声明周期的钩子方法。

    init-method:提供Bean初始化时调用方法
    destroy-method:提供Bean销毁时调用方法
    <bean id="auditorium" class="single.spring.Auditorium" init-method="turnOnLights" destroy-method="turnOffLights"></bean>

    六、注入Bean属性(属性值为单个值)

     使用setter方法注入Bean中的成员属性,前提是存在标准的Setter方法,使用property标签实现,name对应Bean中的成员属性名称,如果属性类型为基本数据类型就用value,如果为引用类型则用ref。 

    <bean id="kenny" class="single.spring.Instrumentalist">
            <!--Setter 基本数据类型,用value -->
            <property name="song" value="Jingle Bells"></property>
            <!--Setter 引用类型,用ref -->
            <property name="instrument" ref="saxophone"></property>
        </bean>
        <bean id="saxophone" class="single.spring.Saxophone"></bean>

     也可以使用内部Bean注入的方式实现成员属性赋值。缺点是内部Bean没有属性ID,导致不能被复用。

    <bean id="kenny" class="single.spring.Instrumentalist">
            <!--Setter 基本数据类型,用value -->
            <property name="song" value="Jingle Bells"></property>
            <!--Setter 引用类型,用内部Bean -->
            <property name="instrument">
                <bean class="single.spring.Saxophone"></bean>
            </property>
        </bean>

    七、装配集合(属性值为集合)

    <list> 装配list类型的值,允许重复,适用数组或者java.util.Collection

    <set> 装配Set类型的值,不允许重复,适用数组或者java.util.Collection

    <map> 装配Map类型的值,名称和值可以是任意类型,java.util.Map

    <props> 装配properties类型的值,名称和值必须都是String型,java.util.Properties

    1 装配List、Set和Array

    成员属性为Collection或Array时都可以,利用List或者Set都可以,可以嵌套适用。

    <bean id="hank" class="single.spring.OneManBank">
            <property name="instruments"><!-- 成员属性 -->
                <list><!-- Collection or Array 类型-->
                    <ref bean="guitar" /> <!-- 引用类型,基本数据类型则为value -->
                    <ref bean="cymbal" /> <!-- 还可以为list set 等-->
                    <ref bean="harmonica" />
                </list>
            </property>
        </bean>

    2 装配Map集合

    <bean id="hank" class="single.spring.OneManBank">
            <property name="instruments"><!-- 成员属性 -->
                <map><!-- 只能为Map -->
                    <entry key="GUITAR" value-ref="guitar"></entry><!-- 根据key value类型可以选择 key key-ref value value-ref>
                    <entry key="CYMBAL" value-ref="cymbal"></entry><!-- 根据key value类型可以选择 key key-ref value value-ref>
                    <entry key="HARMONICA" value-ref="harmonica"></entry><!-- 根据key value类型可以选择 key key-ref value value-ref>
                    <entry 
                </map>
            </property>
        </bean>

    3 装配Properties集合

    成员属性为Properties时需要用下面,Properties就是key和value均为String类型的Map

    <bean id="hank" class="single.spring.OneManBank">
            <property name="instruments"><!-- 成员属性 -->
                <props>
                    <prop key="GUITAR">STRUM STRUM STRUM</prop>
                    <prop key="CYMBAL">CRASH CRASH CRASH</prop>
                    <prop key="HARMONICA">HUM HUM HUM</prop>
                </props>
            </property>
        </bean>

    八、装配空值

    当需要给成员属性赋值为空时,可以使用如下:

    <property name="instruments"><null></null></property>

    九、使用SpEL表达式装配

  • 相关阅读:
    python 基础2.5 循环中continue与breake用法
    python 基础 2.4 while 循环
    python 基础 2.3 for 循环
    python 基础 2.2 if流程控制(二)
    python 基础 2.1 if 流程控制(一)
    python 基础 1.6 python 帮助信息及数据类型间相互转换
    python 基础 1.5 python数据类型(四)--字典常用方法示例
    Tornado Web 框架
    LinkCode 第k个排列
    LeetCode 46. Permutations
  • 原文地址:https://www.cnblogs.com/yaochc/p/5006081.html
Copyright © 2011-2022 走看看