程序员

二、Spring容器中的Bean

2017-03-04  本文已影响176人  数独题

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


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

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

为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种作用域:

实例:
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方法、构造器参数指定参数值:

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

注入嵌套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配置文件也不同:

注入集合值:

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.../>元素又可以接收如下子元素:

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

组合属性:

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

Spring中的Bean和JavaBean:

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

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

上一篇下一篇

猜你喜欢

热点阅读