Spring实例化bean如何决定用JDK反射或CGLIB时机

getbean时,如果没有用代理,如果bean没有配置lookup-method和replace-method则采用JDK反射否则使用CGLIB

在Spring源代码中有这样一段代码
    public Object instantiate(
            RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {

        // Don't override the class with CGLIB if no overrides.
        if (beanDefinition.getMethodOverrides().isEmpty()) {
            return BeanUtils.instantiateClass(beanDefinition.getBeanClass());
        }
        else {
            // Must generate CGLIB subclass.
            return instantiateWithMethodInjection(beanDefinition, beanName, owner);
        }
    }

那么究竟什么时候使用JDK来创建Bean,什么时候使用CGLIB来创建Bean呢?
我注意到源代码中有以下的表述
// Don't override the class with CGLIB if no overrides.
if (beanDefinition.getMethodOverrides().isEmpty()) {
……
}

那么是什么条件才会触发这个MethodOverrides呢?
其实是Spring配置文件中的lookup-method和replace-method,
这其实是两个方法级别的注入,和一般的属性(Property)注入是不一样的,
它们注入的是方法(Method)。
两者的差别是这样的

  1. 如果需要替换的方法没有返回值,那么只能使用replace-method来替换,而不能用lookup-method来替换。
  2. replace-method必须实现MethodReplacer接口的Bean才能替换,而lookup-method则由BeanFactory自动为我们处理了。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值