spring look-method的使用

21 篇文章 0 订阅

作用:用于代理当前bean指定的get方法的,使得该bean的get方法的返回值为注入的bean。

具体:

1、作为返回值的类
public class Test {
}

2、要使用lookup-method标签的测试bean

public class TestBean{
    public Test getTest() {
        System.out.println("被代理了,还会执行吗");
        return null;
    }
}

3、在spring的xml配置文件中配置如下:

<bean id="test" class="com.mine.bean.Test" scope="prototype"/>
    
<bean id="testBean"  class="com.mine.bean.TestBean" scope="singleton">
        <lookup-method name="getTest" bean="test"/>
</bean>

这个配置的作用就是把test这个bean的值(并且是支持scope的)作为testBean的getTest方法的返回值。

而test的scope是prototype,所以每次调用testBean.getTest方法获取到的Test对象都是不同的对象,这样就避免了因为testBean是单例的,使得test被注入后也变成单例的了,这就不太符合scope设置为prototype的初衷。

 

4、main方法指定代码如下:

        XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
        bf.ignoreDependencyInterface(SetterHHHHHAware.class);
        TestBean testBean = bf.getBean("testBean", TestBean.class);
        System.out.println(testBean.getTest().toString());
        System.out.println(testBean.getTest().toString());

5、输出结果如下

com.mine.bean.Test@7b49cea0
com.mine.bean.Test@887af79

输出的不是同一个对象,符合Test在spring中scope为prototype 的配置。

以上就是lookup-method的作用。

 

然后根据我的猜测,代理应该是spring重新实现了getTest方法。大致如下:

public Test getTest(){
    return (Test)SpringUtil.getContext().getBean(Test.class);
}

其中,SpringUtil是我自己建的,context是存储spring上下文的静态字段。。。spring代理类通过其他方式一样可以做到这样,我这里就是模拟。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值