lookup-method方法理解

概念

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值