美文网首页程序员
二、Spring容器中的Bean

二、Spring容器中的Bean

作者: 数独题 | 来源:发表于2017-03-04 09:24 被阅读176次

    Bean的基本定义和Bean的别名:


    <beans.../>元素是Spring配置文件的根元素,该元素可以指定如下属性:

    • default-lazy-init:指定该元素下所有的Bean默认的延迟初始化行为。
    • default-merge:指定该元素下所有的Bean默认的merge行为。
    • default-autowire:指定该元素下所有的Bean默认的自动装配行为。
    • default-autowire-candidates:指定该元素下所有的Bean默认是否作为自动装配的候选Bean。
    • default-init-method:指定该元素下所有的Bean默认的初始化行为。
    • default-destory-method:指定该元素下所有Bean默认回收方法。

    <beans.../>元素所指定的属性都可以在每个<bean.../>子元素中指定,将属性名去掉default即可。区别在于<bean.../>元素下指定的行为值对特定的Bean起作用。<bean.../>元素是<beans.../>元素的子元素,<beans.../>元素可以包含多个<bean.../>子元素,每个<bean.../>元素定义一个Bean,每个Bean对应Spring中的一个Java实例。

    为Bean指定别名:

    • 定义<bean.../>元素是通过为name属性指定别名。
    • 通过<alias.../>元素为已有的Bean指定别名。
    <!--下面为该Bean指定三个别名:123,abc,@123-->
    <bean id="persion" class="..." name="123,abc,@123"/>
    <alias name="persion" alias="jack"/>
    <alias name="jack" alias="jackee"/>
    

    容器中Bean的作用域:

    Spring支持的5种作用域:

    • singleton:singleton作用域的Bean在整个IOC容器中只生成一个实例。
    • prototype:每次通过容器的getBean()方法获取prototype作用域的Bean时,都将产生一个新的Bean实例。
    • request:在同一次HTTP请求中request作用域只产生一个实例。
    • session:在同一次HTTP会话中session作用域只产生一个实例。
    • global session:每个全局的HTTP Session对应一个Bean实例。

    实例:
    Beans.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:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd" >
        <!-- 配置一个singleton Bena实例 -->
       <bean id="chinese1" class="entity.Chinese"/>
       <!-- 配置一个prototype Bean实例 -->
       <bean id="chinese2" class="entity.Chinese" scope="prototype"/>
       
       <bean id="date" class="java.util.Date"/>
    </beans>
    

    BeanTest.java

    package test;
    
    import inter.Persion;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class BeanTest {
    
        public static void main(String[] args) throws Exception
        {
            //创建spring容器
            ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
            //判断两次请求singleton作用域的Bean实例是否相等
            System.out.println(ctx.getBean("chinese1")==ctx.getBean("chinese1"));
            //判断两次请求prototype作用域的Bean实例是否相等
            System.out.println(ctx.getBean("chinese1")==ctx.getBean("chinese2"));
            System.out.println(ctx.getBean("date"));
            Thread.sleep(1000);
            System.out.println(ctx.getBean("date"));
        }
        
    }
    
    

    输出

    true
    false
    Fri Mar 03 20:59:54 CST 2017
    Fri Mar 03 20:59:54 CST 2017
    

    request和session作用域只在Web应用中才有效,并且必须在Web应用中添加额外的配置才会生效。必须将HTTP请求对象绑定到为该请求提供服务的线程上。

    对于Servlet2.4,在web.xml中增加Listener使request作用域生效:

    <listener>
      <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    

    配置依赖:

    通常不建议使用配置文件管理Bean的基本类型的属性值,通常使用配置文件管理容器中Bean与Bean之间的依赖关系。
    BeanFactory和ApplicationContext实例化容器中的Bean的时机不同,前者等到需要Bean实例时才执行初始化,后者在容器创建ApplicationContext实例时,会预先初始化容器中所有的singleton Bean。

    Spring允许通过如下元素为setter方法、构造器参数指定参数值:

    • value
    • ref
    • bean
    • list、set、map、props

    使用自动装配注入合作者Bean:

    • no:不使用自动装配。
    • byName:根据setter方法名进行自动装配。
    • byType:根据setter方法的形参类型来自动装配。
    • constructor:与byType类似,区别是用于自动匹配构造器的参数。
    • autodetect:Spring容器根据Bean内部结构,自行决定使用constructor或byType策略。

    注入嵌套Bean:

    如果某个Bean不想被Spring容器直接访问,则可以使用嵌套Bean。把<bean.../>配置成<property.../>或者<constructor-args.../>的子元素,那么该<bean.../>元素配置的Bean仅仅作为setter注入、构造注入的参数,这种Bean就是嵌套Bean。

    beans.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:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd" >
       <!-- 使用嵌套Bean作为参数 -->
       <bean id="chinese" class="entity.Chinese">
         <property name="axe" >
         <!-- 嵌套Bean配置对象仅作为setter方法的参数,嵌套Bean不能被容器访问,因此无需指定id属性 -->
            <bean class="entity.StoneAxe"/>
         </property>
       </bean>
    </beans>
    

    嵌套Bean提高了程序的内聚性,但是降低了程序的灵活性,只有在完全确定了Spring容器无需访问某个Bean时才考虑用嵌套Bean来配置该Bean。

    随着参数的不同,Spring通过setter或者有参数的构造器传入参数时,Spring配置文件也不同:

    • 形参类型是基本类型、String、Date等,直接使用value指定字面值即可。
    • 形参类型是复合类(Persion、Axe)时,1、使用ref应用容器中的已配置的Bean,2、使用<bean.../>元素来配置一个嵌套Bean。

    注入集合值:

    Chinese.java

    package entity;
    
    import java.util.List;
    import java.util.Map;
    import java.util.Properties;
    import java.util.Set;
    
    import inter.Axe;
    import inter.Persion;
    
    public class Chinese implements Persion {
    
        //集合类型的成员变量
        private List<String> schools;
        private Map scores;
        private Map<String,Axe> phaseAxe;
        private Properties health;
        private Set axes;
        private String[] books;
        public Chinese()
        {
            System.out.println("Spring实例化主调Bean:Chinese实例。。。。");
        }
        @Override
        public void useAxe() {
            // TODO Auto-generated method stub
            
        }
        public void setSchools(List<String> schools) {
            this.schools = schools;
        }
        public void setScores(Map scores) {
            this.scores = scores;
        }
        public void setPhaseAxe(Map<String, Axe> phaseAxe) {
            this.phaseAxe = phaseAxe;
        }
        public void setHealth(Properties health) {
            this.health = health;
        }
        public void setAxes(Set axes) {
            this.axes = axes;
        }
        public void setBooks(String[] axes) {
            this.books = books;
        }
        public void test()
        {
            System.out.println(schools);
            System.out.println(scores);
            System.out.println(phaseAxe);
            System.out.println(health);
            System.out.println(axes);
            System.out.println(java.util.Arrays.toString(books));
        }
    
    }
    
    

    beans.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:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd" >
       <bean id="chinese" class="entity.Chinese">
         <property name="schools" >
            <!-- 为调用setSchools()方法配置List集合作为参数值 -->
            <list>
              <value>小学</value>
              <value>中学</value>
              <value>大学</value>
            </list>
         </property>
         <property name="scores" >
            <!-- 为调用setScores()方法配置Map集合作为参数值 -->
            <map>
             <entry key="数学" value="87"/>
             <entry key="语文" value="87"/>
             <entry key="英语" value="87"/>
            </map>
         </property>
         <property name="phaseAxes" >
            <!-- 为调用setPhaseAxes()方法配置Map集合作为参数值 -->
            <map>
            <!-- 每个entry配置一个value-ref -->
             <entry key="原始社会" value-ref="stoneAxe"/>
             <entry key="农业社会" value-ref="steelAxe"/>
            </map>
         </property>
         <property name="health" >
            <!-- 为调用setHealth()方法配置Properties集合作为参数值 -->
            <props>
               <prop key="血压">正常</prop>
               <prop key="升高">175</prop>
            </props>
         </property>
        <!-- .............. -->
       </bean>
    </beans>
    

    使用<list.../>、<set..../>、<map.../>等元素配置集合类型的参数值时,还需要配置集合元素。由于集合元素又可以是基本类型值 ,应用容器中的其他Bean、嵌套Bean或集合属性,所以<list.../>、<set..../>、<map.../>元素又可以接收如下子元素:

    • value
    • ref
    • bean
    • list、set、map、props。

    <key.../>的子元素又可以是value、ref、 bean、 list、 set、 map、 props。

    组合属性:

    使用配置文件形如foo.bar.name的属性设置参数值,为Bean的组合设置参数值时,除了最后一个属性之外,其他属性都不能为空。组合属性只有最后一个属性使用setter方法,前面的个属性都使用getter方法。

    Spring中的Bean和JavaBean:

    Spring中的Bean应满足如下原则:

    • 尽量为每个Bean提供无参数的构造函数。
    • 接受构造注入的Bean应该提供对应的、带参数的构造方法。
    • 接受设值注入的Bean应该提供对应的setter方法。

    传统的JavaBean和Spring中的Bean的区别:

    • 用处不同:传统的JavaBean更多是作为值传递参数,Spring的Bean无所不包,几乎所有的应用组件都被称为Bean。
    • 写法不同:传统的JavaBean作为值对象,要求每个属性都提供getter和setter方法,Spring中的Bean在进行设值注入时只需要提供属性的setter方法。
    • 生命周期不同:传统的JavaBean作为值传递对象,不接受任何容器管理其生命周期,Spring中的Bean有Spring容器管理其生命周期。

    相关文章

      网友评论

        本文标题:二、Spring容器中的Bean

        本文链接:https://www.haomeiwen.com/subject/hairgttx.html