Spring lookup-method analysis

1: Usage

By defining an abstract class and an abstract method, use the abstract method to obtain the required bean. The role is to achieve the flexibility of the bean, pluggable, when the specified bean does not meet our needs, only need to modify lookup-methodthe nameattributes in the tag in the configuration file , without the need to modify the code.

2: Examples

2.1: Define the class used to define the bean

public class MyLookUpMethodCls {
    
    
}

2.2: Define abstract classes

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

2.3: Configuration file

<?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 code

@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());
}

run:

yudaosourcecode.lookupmethod.MyLookUpMethodCls@6b67034

Process finished with exit code 0

Method is myLookUpMethodAbstractCls.returnMyLookUpMethodCls()equivalent to code ac.getBean("myLookUpMethodCls").

Guess you like

Origin blog.csdn.net/wang0907/article/details/114321253