spring的容器配置文件

spring的容器配置文件

<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">

    <!-- 定义一个Bean -->
    <bean id="myBean" class="com.example.MyClass" scope="singleton" lazy-init="false" init-method="init" destroy-method="destroy">
        
        <!-- 设置构造函数注入 -->
        <constructor-arg index="0" value="constructorValue"/>
        <constructor-arg index="1" ref="anotherBean"/>
        
        <!-- 设置属性注入 -->
        <property name="propertyName" value="propertyValue"/>
        <property name="anotherProperty" ref="anotherBean"/>

        <!-- 内部bean -->
        <property name="innerBean">
            <bean class="com.example.InnerClass">
                <property name="innerProperty" value="innerValue"/>
            </bean>
        </property>

        <!-- 使用p:命名空间简化属性注入 -->
        <!-- xmlns:p="http://www.springframework.org/schema/p" 需要在<beans>标签中声明 -->
        <!-- <bean id="myBean" class="com.example.MyClass" p:propertyName="propertyValue" p:anotherProperty-ref="anotherBean"/> -->

        <!-- 使用c:命名空间简化构造函数注入 -->
        <!-- xmlns:c="http://www.springframework.org/schema/c" 需要在<beans>标签中声明 -->
        <!-- <bean id="myBean" class="com.example.MyClass" c:index1-ref="anotherBean" c:index0="constructorValue"/> -->

    </bean>

</beans>

spring中bean标签的scope属性中的singleton并不是单例模式,而是此bean标签的对应的bean是单例的,如果另写一个bean标签但是class属性的值是一样的或者说指向同一个类,此类就不是单例的的,仅仅只是代表bean标签的作用域,而不能代表所指类的构建模式,例如:

<bean id="myBean" class="com.example.MyClass" scope="singleton">

</bean>


<bean id="yourBean" class="com.example.MyClass" scope="singleton">

</bean>

上面定义的两个bean标签都是单例的,即通过‘myBean’和’yourBean‘获取的对象都是单例的都是同一个对象,但是com.example.MyClass这个类并不是单例的

在Spring的XML配置中,<constructor-arg> 标签用于为Bean的构造函数注入参数。虽然使用 index 属性是指定参数位置的一种方式,但它不是唯一的方式。实际上,我们可以不用 index 属性,而是用其他方式来指定构造函数参数。

使用 index 属性:

<bean id="myBean" class="com.example.MyClass">
    <constructor-arg index="0" value="constructorValue"/>
    <constructor-arg index="1" ref="anotherBean"/>
</bean>

使用 type 属性:

<bean id="myBean" class="com.example.MyClass">
    <constructor-arg type="java.lang.String" value="constructorValue"/>
    <constructor-arg type="com.example.AnotherClass" ref="anotherBean"/>
</bean>

按顺序定义(无 indextype):

<bean id="myBean" class="com.example.MyClass">
    <constructor-arg value="constructorValue"/>
    <constructor-arg ref="anotherBean"/>
</bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值