spring的lookup-method分析

1: 用法

通过定义一个抽象类,并定义一个抽象方法,使用该抽象方法获取需要的bean。作用是实现bean的灵活性,可插拔,当指定的bean不满足我们的需求时,只需要修改配置文件中的lookup-method标签中的name属性就可以了,而不需要修改代码。

2:实例

2.1:定义用于定义bean的类

public class MyLookUpMethodCls {
    
    
}

2.2:定义抽象类

public abstract class MyLookUpMethodAbstractCls {
    
    
    public abstract MyLookUpMethodCls returnMyLookUpMethodCls();
}

2.3:配置文件

<?xml version="1.0" encoding="UTF-8"?>
<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 id="myLookUpMethodCls" class="yudaosourcecode.lookupmethod.MyLookUpMethodCls"/>

    <bean id="myLookUpMethodAbstractCls" class="yudaosourcecode.lookupmethod.MyLookUpMethodAbstractCls">
        <!-- 通过方法returnMyLookUpMethodCls获取bean名称为myLookUpMethodCls的bean -->
        <lookup-method bean="myLookUpMethodCls" name="returnMyLookUpMethodCls"/>
    </bean>
</beans>

2.4:测试代码

@Test
public void testLookUpMethod() {
    
    
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:testlookupmethod.xml");
    MyLookUpMethodAbstractCls myLookUpMethodAbstractCls = ac.getBean("myLookUpMethodAbstractCls", MyLookUpMethodAbstractCls.class);
    // 通过调用方法的方式来获取MyLookUpMethodCls的bean
    System.out.println(myLookUpMethodAbstractCls.returnMyLookUpMethodCls());
}

运行:

yudaosourcecode.lookupmethod.MyLookUpMethodCls@6b67034

Process finished with exit code 0

方法myLookUpMethodAbstractCls.returnMyLookUpMethodCls()等同于代码ac.getBean("myLookUpMethodCls")

猜你喜欢

转载自blog.csdn.net/wang0907/article/details/114321253