Spring中 lookup-method 用法

本文详细介绍了Spring框架中方法注入的使用场景与实现方式。通过具体的示例,展示了如何利用lookup-method属性来解决单例Bean与原型Bean之间的依赖问题。

1、官方文档解释

If the method is abstract, the dynamically-generated subclass implements the method. Otherwise,
the dynamically-generated subclass overrides the concrete method defined in the original class. For
example:


<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="command" class="fiona.apple.AsyncCommand" scope="prototype">
<!-- inject dependencies here as required -->
</bean>
<!-- commandProcessor uses statefulCommandHelper -->
<bean id="commandManager" class="fiona.apple.CommandManager">
<lookup-method name="createCommand" bean="command"/>
</bean>
 

2、 个人测试

2.1 Spring中的配置

 <!-- 
        方法注入:
         因为两个bean的生存周期可能不一致,但是他们之间有相互的关联。
         举例来说,一个单例的bean A 需要一个非单例的原型bean B。
         Spring容器只初始化A一次。因此只有一次机会设置B。所以A无法每次在需要的时候提供一个新的对象B。
     -->
    <bean id="people" class="cyz.method.injection.People" scope="prototype">
        <property name="name" value="群演"></property>
    </bean>
    
    <bean id="movie" class="cyz.method.injection.Movie" scope="singleton">
        <lookup-method name="getActor" bean="people"></lookup-method>
    </bean>

 

其中Movie是一个接口,它没有任何实现类。

通过lookup-meghod可以创建一个实现了Movie接口的类,然后可以调用它的getMethod方法取得名为people的bean。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值