Spring的lookup-method标签

Spring的解析源码

    public void parseLookupOverrideSubElements(Element beanEle, MethodOverrides overrides) {
        NodeList nl = beanEle.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            //仅当在Spring默认bean的子元素下且为
       if (isCandidateElement(node) && nodeNameEquals(node, LOOKUP_METHOD_ELEMENT)) { Element ele = (Element) node; //获取要修饰的方法
          String methodName
= ele.getAttribute(NAME_ATTRIBUTE); //获取配置返回的bean
          String beanRef
= ele.getAttribute(BEAN_ELEMENT); LookupOverride override = new LookupOverride(methodName, beanRef); override.setSource(extractSource(ele)); overrides.addOverride(override); } } }

lookup-method的使用

lookup-method实现方式说明:

<bean class="beanClass">
    <lookup-method name="method" bean="non-singleton-bean"/>
</bean>
// 定义一个水果类
public class Fruit {
    public Fruit() {
        System.out.println("I got Fruit");
    }
}
// 苹果
public class Apple extends Fruit {
    public Apple() {
        System.out.println("I got a fresh apple");
    }
}
// 香蕉
public class Bananer extends Fruit {
    public Bananer () {
        System.out.println("I got a  fresh bananer");
    }
}
// 水果盘,可以拿到水果
public abstract class FruitPlate{
    // 抽象方法获取新鲜水果
    protected abstract Fruit getFruit();
}
<!-- 这是2个非单例模式的bean -->
<bean id="apple" class="Apple" scope="prototype"/>
<bean id="bananer" class="Bananer " scope="prototype"/>
<bean id="fruitPlate1" class="FruitPlate">
    <lookup-method name="getFruit" bean="apple"/>
</bean>
<bean id="fruitPlate2" class="FruitPlate">
    <lookup-method name="getFruit" bean="bananer"/>
</bean>


public static void main(String[] args) {
    ApplicationContext app = new ClassPathXmlApplicationContext("classpath:resource/applicationContext.xml");
    FruitPlate fp1= (FruitPlate)app.getBean("fruitPlate1");
    FruitPlate fp2 = (FruitPlate)app.getBean("fruitPlate2");
    fp1.getFruit();
    fp2.getFruit();
}

测试结果:
I got Fruit
I got a fresh apple
I got Fruit
I got a fresh bananer

 

posted @ 2016-11-16 09:57  wade&luffy  阅读(482)  评论(0编辑  收藏  举报