bean实例化策略
spring中反射实例化规范
InstantiationStrategy源码
无参构造方法实例化
默认情况下的反射实例化bean方式。
Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner)
指定构造方法实例化
指定 或 选择最合适的构造器,完成bean的实例化。
Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner, Constructor<?> ctor, Object... args)
工厂方法实例化
xml文件中bean的factory-method属性,实际实例化bean方式。
Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner, @Nullable Object factoryBean, Method factoryMethod, Object... args)
SimpleInstantiationStrategy实现类
实现了InstantiationStrategy接口,完成三个方法对应实现,扩展设计两个接口。
实例化 无参数构造器 的代理对象
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
}
实例化 有参数构造器 的代理对象
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner, @Nullable Constructor<?> ctor, Object... args) {
throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
}
CglibSubclassingInstantiationStrategy实现类
继承SimpleInstantiationStrategy,完成代理对象 有参数和无参数 创建方法。
源码
此实现类中包含两个很有趣的内部类:ReplaceOverrideMethodInterceptor和LookupOverrideMethodInterceptor,分别对应spring中实例化bean方式中的 replace-method和lookup-method方法。
总结
spring中的反射创建对象、replace-method、lookup-method、factory-method创建对象,本质上都是通过实例化策略InstantiationStrategy完成对象的实例化。
有兴趣可以在具体实现流程。<感觉没必要继续看下去,就是反射创建对象>