7.2Java EE——Bean的配置

Spring容器所支持的配置文件格式

        Spring容器支持XML和Properties两种格式的配置文件,在实际开发中,最常用的是XML格式的配置文件。XML是标准的数据传输和存储格式,方便查看和操作数据。在Spring中,XML配置文件的根元素是<beans>,<beans>元素包含<bean>子元素,每个<bean>子元素可以定义一个Bean,通过<bean>元素将Bean注册到Spring容器中。 

<bean>元素的常用属性 

属性

描述

id

id属性是<bean>元素的唯一标识符,Spring容器对Bean的配置和管理通过id属性完成,

装配Bean时也需要根据id值获取对象。

name

name属性可以为Bean指定多个名称,

每个名称之间用逗号或分号隔开。

class

class属性可以指定Bean的具体实现类,其属性值为对象所属类的全路径。

scope

scope属性用于设定Bean实例的作用范围,

其属性值有:singleton(单例)、prototype(原型)、request、session和global session。

 <bean>元素的常用子元素

元素

描述

<constructor-arg>

使用<constructor-arg>元素可以为Bean的属性指定值。

<property>

<property>元素的作用是调用Bean实例中的setter方法完成属性赋值,

从而完成依赖注入。

ref

ref是<property>、<constructor-arg>等元素的属性,

可用于指定Bean工厂中某个Bean实例的引用;

也可用于指定Bean工厂中某个Bean实例的引用。

value

value是<property>、<constructor-arg>等元素的属性,

用于直接指定一个常量值;也可以用于直接指定一个常量值。

<list>

<list>元素是<property>等元素的子元素,

用于指定Bean的属性类型为List或数组。

<set>

<set>元素是<property>等元素的子元素,

用于指定Bean的属性类型为set。

<map>

<map>元素是<property>等元素的子元素,

用于指定Bean的属性类型为Map。

<entry>

entry>元素是<map>元素的子元素,用于设定一个键值对。

<entry>元素的key属性指定字符串类型的键。

普通的Bean通常只需定义id(或者name)和class两个属性 

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--使用id属性定义bean1,对应的实现类为com.mac.Bean1-->
    <bean id="bean1" class="com.mac.Bean1">
    </bean>
    <!--使用name属性定义bean2,对应的实现类为com.mac.Bean2-->
    <bean name="bean2" class="com.mac.Bean2"/>
</beans>

猜你喜欢

转载自blog.csdn.net/W_Fe5/article/details/131667756