概念
lookup-method一旦应用,Spring框架会自动使用CGLIB技术为指定类型动态创建一个动态子类型,并自动实现抽象方法。可以动态的实现依赖注入的数据准备。
应用场景
可以只提供 lookup-method 方 法的返回值对象即可实现动态的对象返回。 在工厂方法难以定制的时候使用。 也是模板的一种应用。是工厂方法的扩展。 如:工厂方法返回对象类型为接口类型。且不同版本应用返回的对象未必相同时使用。 可以避免多次开发工厂类。
代码实现
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestLookupMethod{
public static void main(String[] args){
ApplicationContext context= new ClassPathXmlApplicationContext("classpath:lookupmethod/applicationContext.xml");
CommandManager manager = context.getBean("manager",CommandManager.class);
System.out.println(manager.getClass().getName()); manager.process();
}
}
abstract class CommandManager{
public void process(){
MyCommandcommand=createCommand(); //dosomething... System.out.println(command);
}
protected abstract MyCommand createCommand();
}
class MyCommand{
publicMyCommand(){
System.out.println("MyCommandinstanced");
} }
<beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="manager"class="com.xxx.lookupmethod.CommandManager"> <lookup-method bean="command"name="createCommand"/> </bean>
<bean id="command"class="com.xxx.lookupmethod.MyCommand"></bean>
</beans>