• Spring学习之二


      1.初始化和销毁Bean

    当实例化一个Bean时,可能需要执行一些初始化操作来确保该Bean处于可用状态。同样地,当不需要Bean时,将其从容器中移除时,我们可能还需要按顺序的执行一些清除工作。

    为定义Bean初始化和销毁操作,只需要使用init-method和destroy-method参数来配置<bean>元素。

    首先定义两个方法

    public class Test{
        public void hello1(){
        }
    
        public void hello2(){
        }    
    }
    

      配置Bean

    <bean class="Test" init-method="hello1"  destroy-method="hello2"> 
    
    </bean>
    

      上述配置后,Test Bean在实例化后立即调用hello1()方法。在该Bean从容器移除或销毁前,会调用hello2()方法。

    如果在上下文定义的很多Bean拥有相同的初始化方法和销毁方法,这时候没有必要为每一个<bean>声明init-method和destroy-method属性。可以使用<beans>元素的default-init-method和default-destroy-method属性

    2.注入属性

    <properties>标签

    为了不和其他类公用一个类对象,可以注入内部Bean来解决,内部Bean仅供该对象使用。

    3.引用其他Bean

    <bean class="Test" init-method="hello1"  destroy-method="hello2"> 
        <properties name="propertiesName" value="propertiesValue"/>
        <properties name="objectName">
            <bean class="OtherClass"/>
        </properties>
    </bean>
    

      内部Bean没有Id属性。

     

    4.使用Spring的命名空间p装配属性

    使用p命名空间需要在Spring配置文件添加如下配置

    xmlns:p="http://www.springframework.org/schema/p"

    使用p命名空间的配置方式:

    <bean class="Test" init-method="hello1"  destroy-method="hello2"
        p:propertiesName = "value"
        p:objectName-ref = "calssName" /> 
    

    5.装配List、Set、Map和Props属性

    6.使用表达式装配属性

    上述Bean的装配方式在配置文件中定义好了,但是如果我们为属性装配的值只有在运行期才能知道,可以利用表达式装配。SpEL表达式能通过运行期执行表达式将值装配到Bean的属性或构造器参数中。

  • 相关阅读:
    opendressinghash //use resize array
    ChainingHash
    Hash function
    stack && queue
    random_select
    counting sort
    master theorem
    各排序算法及其比较
    视图中添加主键的方法
    oracle表空间的扩展
  • 原文地址:https://www.cnblogs.com/zhangyongJava/p/8337501.html
Copyright © 2020-2023  润新知