Spring中单例bean中使用多例

创建PrototypeDemoLM.java文件提供多例

public class PrototypeDemoLM {
}

创建SingletonDemoLM.java文件,将PrototypeDemoLM依赖

public class SingletonDemoLM {
    private PrototypeDemoLM prototypeDemoLM;

    public PrototypeDemoLM getPrototypeDemoLM() {
        return prototypeDemoLM;
    }

    public void setPrototypeDemoLM(PrototypeDemoLM prototypeDemoLM) {
        this.prototypeDemoLM = prototypeDemoLM;
    }
}

配置文件
PrototypeDemoLM的bean为多例,SingletonDemoLM 设为单例

<bean id="prototypeDemoLM" class="com.example.demo.demo.PrototypeDemoLM" scope="prototype"></bean>
    <bean id="singletonDemoLM" class="com.example.demo.demo.SingletonDemoLM">
		<property name="prototypeDemoLM" ref="prototypeDemoLM"></property>
    </bean>

使用property标签创建关联
测试类

 @Test
    void contextLoads() {
        System.out.println("spring容器启动中...");
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        System.out.println(context.getBean(PrototypeDemoLM.class));
        System.out.println(context.getBean(SingletonDemoLM.class));
        SingletonDemoLM singletonDemoLM = context.getBean(SingletonDemoLM.class);
        System.out.println(singletonDemoLM.getPrototypeDemoLM());
        System.out.println("spring容器启动完毕!");

    }

控制台打印结果

spring容器启动中...
com.example.demo.demo.PrototypeDemoLM@5d1b9c3d
com.example.demo.demo.SingletonDemoLM$$EnhancerBySpringCGLIB$$508bc356@69e05f61
com.example.demo.demo.PrototypeDemoLM@49a26d19
spring容器启动完毕!

PrototypeDemoLM创建出不同的实例
但是用到spring中的接口ApplicationContextAware,此时对spring的api有耦合的作用,可以使用spring的标签实现样的效果

 <bean id="prototypeDemoLM" class="com.example.demo.demo.PrototypeDemoLM" scope="prototype"></bean>
    <bean id="singletonDemoLM" class="com.example.demo.demo.SingletonDemoLM">
        <lookup-method name="getPrototypeDemoLM" bean="prototypeDemoLM"></lookup-method>
<!--        <property name="prototypeDemoLM" ref="prototypeDemoLM"></property>-->
    </bean>

控制台打印结果

spring容器启动中...
com.example.demo.demo.PrototypeDemoLM@bdd2027
com.example.demo.demo.SingletonDemoLM$$EnhancerBySpringCGLIB$$508bc356@31f20c9f
com.example.demo.demo.PrototypeDemoLM@f446158
spring容器启动完毕!

lookup-method:看其名字,就知道意思:方法查找,调用name属性指定的方法的时候,spring会对这个方法进行拦截,然后去容器中查找lookup-method元素中bean属性指定的bean,然后将找到的bean作为方法的返回值返回。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值