之前在《关于@Bean的full模式和lite模式》一文中写了在@Configuration注解标记的类中使用@Bean注解生成对象和在@Component注解标记的类中使用@Bean注解生成对象的区别,今天来说一下在@Configuration注解标记的类中生成单例Bean的原理。
ConfigurationClassPostProcessor的postProcessBeanFactory
之前说过,使用@Configuration标记的类会被Sping标记成full模式,那具体这个full是什么时候应用的呢?
至于postProcessBeanFactory方法是什么时候被触发的,这里不再赘述。我们直接来看
ConfigurationClassPostProcessor的postProcessBeanFactory
如上图所示,这两个方法的作用是为full模式的类创建代理类,然后使用
ImportAwareBeanPostProcessor后置处理接口在属性注入的时候,为该类注入beanFactory,至于为什么,我们一点一点来看。
enhanceConfigurationClasses:创建代理类
通过下面的代码,我们可以初步理解到,当当前的BeanDefinition是full模式的时候,会被创建代理类。
public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<>();
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
//判断当前处理的BeanDefinition是否是full模式,是的话,添加到map中
if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) {
...
configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
}
}
//没有配置类,直接返回
if (configBeanDefs.isEmpty()) {
// nothing to enhance -> return immediately
return;
}
//用于创建代理类
ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) {
AbstractBeanDefinition beanDef = entry.getValue();
// If a @Configuration class gets proxied, always proxy the target class
//该属性和自动代理时是相关的
beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
try {
// Set enhanced subclass of the user-specified bean class
//Spring是使用CGLIB,而CGLIB是基于继承的方式实现代理,所以这里指定代理类的“父类”类型,也就是当前配置类
Class<?> configClass = beanDef.resolveBeanClass(this.beanClassLoader);
if (configClass != null) {
//开始创建代理类,实际这里返回的就是代理类
Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
//不相等的话,说明创建了代理类,与“父类”不一样
if (configClass != enhancedClass) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Replacing bean definition '%s' existing class '%s' with " +
"enhanced class '%s'", entry.getKey(), configClass.getName(), enhancedClass.getName()));
}
//设置代理类
beanDef.setBeanClass(enhancedClass);
}
}
}
catch (Throwable ex) {
throw new IllegalStateException("Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
}
}
}接下来我们来继续深入,看一下enhancer.enhance()是如何创建代理类的
public Class<?> enhance(Class<?> configClass, @Nullable ClassLoader classLoader) {
if (EnhancedConfiguration.class.isAssignableFrom(configClass)) {
...
return configClass;
}
//创建代理类
Class<?> enhancedClass = createClass(newEnhancer(configClass, classLoader));
...
return enhancedClass;
}
private Enhancer newEnhancer(Class<?> superclass, @Nullable ClassLoader classLoader) {
//spring完全复制了一套CGLIB的动态代理,这里使用的是spring的,但是大致都相同
Enhancer enhancer = new Enhancer();
//设置被代理的类为其父类型
enhancer.setSuperclass(superclass);
//让生成的代理类实现EnhancedConfiguration接口(EnhancedConfiguration接口继承了BeanFactoryAware)
enhancer.setInterfaces(new Class<?>[] {EnhancedConfiguration.class});
//设置生成的代理类不实现org.springframework.cglib.proxy.Factory接口
enhancer.setUseFactory(false);
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
//设置代理类名称的生成策略:Spring定义的一个生成策略:你代理的名称中会有“BySpringCGLIB”字样
//同时给代理类设置一个$beanFactory字段,并设置成BeanFactory类型
enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader));
//这两个是设置拦截器,当目标方法执行的时候进行拦截处理,这里我们下面讲
enhancer.setCallbackFilter(CALLBACK_FILTER);
enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes());
return enhancer;
}
private Class<?> createClass(Enhancer enhancer) {
//创建代理类
Class<?> subclass = enhancer.createClass();
// Registering callbacks statically (as opposed to thread-local)
// is critical for usage in an OSGi environment (SPR-5932)...
Enhancer.registerStaticCallbacks(subclass, CALLBACKS);
return subclass;
}
BeanFactoryAwareGeneratorStrategy:给代理类设置一个$beanFactory字段,并设置成BeanFactory类型
private static class BeanFactoryAwareGeneratorStrategy extends DefaultGeneratorStrategy {
@Nullable
private final ClassLoader classLoader;
public BeanFactoryAwareGeneratorStrategy(@Nullable ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
protected ClassGenerator transform(ClassGenerator cg) throws Exception {
ClassEmitterTransformer transformer = new ClassEmitterTransformer() {
@Override
public void end_class() {
//设置字段
declare_field(Constants.ACC_PUBLIC, BEAN_FACTORY_FIELD, Type.getType(BeanFactory.class), null);
super.end_class();
}
};
return new TransformingClassGenerator(cg, transformer);
}
...
}这里需要注意一下,我们下面讲的拦截器拦截原理是只有在代理对象实例化后且目标方法执行的时候才会拦截。
CALLBACK_FILTER:代理拦截。在CALLBACK_FILTER中,一共设置了三个拦截器。
private static final Callback[] CALLBACKS = new Callback[] {
new BeanMethodInterceptor(),
new BeanFactoryAwareMethodInterceptor(),
//什么也没做
NoOp.INSTANCE
};我们重点来看一下代理对象的拦截方法:
BeanFactoryAwareMethodInterceptor和BeanMethodInterceptor
BeanFactoryAwareMethodInterceptor:实现了MethodInterceptor和ConditionalCallback。熟悉CGLIB动态代理的应该知道,当目标方法执行的时候,会调用MethodInterceptor中的intercept方法,而ConditionalCallback则是条件,判断什么条件才会拦截被代理对象然后进行增强。
通过下面代码的理解,我们可以知道,当目标类中有setBeanFactory方法的时候(具体会更复杂,看下面代码注释)才会被拦截,并给这个字段设置beanFactory。
private static class BeanFactoryAwareMethodInterceptor implements MethodInterceptor, ConditionalCallback {
@Override
@Nullable
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
//获取代理类中的$beanFactory字段
//这里之所以有这个字段,是因为在BeanFactoryAwareGeneratorStrategy中进行了添加
Field field = ReflectionUtils.findField(obj.getClass(), BEAN_FACTORY_FIELD);
Assert.state(field != null, "Unable to find generated BeanFactory field");
//这是beanFactory对象
field.set(obj, args[0]);
// Does the actual (non-CGLIB) superclass implement BeanFactoryAware?
// If so, call its setBeanFactory() method. If not, just exit.
if (BeanFactoryAware.class.isAssignableFrom(ClassUtils.getUserClass(obj.getClass().getSuperclass()))) {
return proxy.invokeSuper(obj, args);
}
return null;
}
//这里说明一下下面的方法:由于代理类实现了EnhancedConfiguration,而EnhancedConfiguration又继承了BeanFactoryAware
//因此,代理对象在创建对象阶段,会进行属性注入,setBeanFactory()是BeanFactoryAware接口的方法,目的是为了获取beanFactory
//因为,当前方法的作用是为了拦截代理对象中有setBeanFactory()方法的类
@Override
public boolean isMatch(Method candidateMethod) {
//判断当前方法的名字是setBeanFactory,并且setBeanFactory方法的参数只有一个,
//并且这个参数的类型是BeanFactory并且返回声明该方法的类对象。即使方法被子类继承,getDeclaringClass()仍返回最初声明的类
return (candidateMethod.getName().equals("setBeanFactory") &&
candidateMethod.getParameterCount() == 1 &&
BeanFactory.class == candidateMethod.getParameterTypes()[0] &&
BeanFactoryAware.class.isAssignableFrom(candidateMethod.getDeclaringClass()));
}
}BeanMethodInterceptor:使用@Bean能产生单例Bean的原因。
如果说上面的代码是引入了beanFactory工具,那么下面的代码就是在@Configuration标记的类中使用@Bean注解获取单例Bean的原因了。
但是这个拦截方法的逻辑太多,我们只看关键的部分:
private static class BeanMethodInterceptor implements MethodInterceptor, ConditionalCallback {
/**
* Enhance a {@link Bean @Bean} method to check the supplied BeanFactory for the
* existence of this bean object.
* @throws Throwable as a catch-all for any exception that may be thrown when invoking the
* super implementation of the proxied method i.e., the actual {@code @Bean} method
*/
@Override
@Nullable
public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object[] beanMethodArgs,
MethodProxy cglibMethodProxy) throws Throwable {
//通过反射获取当前代理对象的beanFactory(上面讲述的代码就是说怎么设置的,这里是怎么获取,里面很简单,就是通过反射,不再赘述)
ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance);
String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod);
// Determine whether this bean is a scoped-proxy
...
// FactoryBean
...
//isCurrentlyInvokedFactoryMethod很关键
if (isCurrentlyInvokedFactoryMethod(beanMethod)) {
if (logger.isWarnEnabled() &&
BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
logger.warn(String.format("@Bean method %s.%s is non-static and returns an object " +
"assignable to Spring's BeanFactoryPostProcessor interface. This will " +
"result in a failure to process annotations such as @Autowired, " +
"@Resource and @PostConstruct within the method's declaring " +
"@Configuration class. Add the 'static' modifier to this method to avoid " +
"these container lifecycle issues; see @Bean javadoc for complete details.",
beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName()));
}
//调用父类的,即代理对象的父类对象的方法,就是我们创建对象的方法
return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
}
//代码太多,简单来说就是通过beanFactory来获取指定的单例bean,而不是再调用我们的方法去创建bean
return resolveBeanReference(beanMethod, beanMethodArgs, beanFactory, beanName);
}
}private boolean isCurrentlyInvokedFactoryMethod(Method method) {
//获取到当前被调用方法和method被拦截的方法是不是同一个
//这里的理解很重要,我们下面说
Method currentlyInvoked = SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod();
//校验method是否和currentlyInvoked为同一个方法
return (currentlyInvoked != null && method.getName().equals(currentlyInvoked.getName()) &&
Arrays.equals(method.getParameterTypes(), currentlyInvoked.getParameterTypes()));
}//这里怎么理解呢?
//举个例子:在下面的这段代码中,被调用的方法是staff(),
//如果被拦截的方法也是staff()的话,则直接调用代理对象的父类方法,也就是我们的方法
@Bean
public Staff staff() {
return new Staff();
}
@Bean
public String equalsStaff(Staff staff) {
System.out.println("invoke others Bean's INSTANCE is "+staff.hashCode());
//但是在这段代码中,被调用的方法是equalsStaff(),而拦截的方法是staff(),
//这个时候,staff()就不会调用父类的(我们自己的),
//而是通过resolveBeanReference方法从beanFactory中获取,因为
System.out.println("invoke Constructor's INSTANCE is "+staff().hashCode());
return "";
} 因此,上面的类生成的代理类可以简单理解成下面的:
public class StaffConfigProxy extends StaffConfig{
BeanFactory $beanFactory;
void setBeanFactory(BeanFactory beanFactory){
this.$beanFactory=beanFactory;
}
@Bean
public Staff staff() {
return new Staff();
}
@Bean
public String equalsStaff(Staff staff) {
//当前入参的地址值
System.out.println("invoke others Bean's INSTANCE is "+staff.hashCode());
//staff()模拟从容器中获取Bean
System.out.println("invoke Constructor's INSTANCE is "+(Staff)$beanFactory.getBean("staff").hashCode());
return "";
}
}ImportAwareBeanPostProcessor:属性注入
我们上面说了一大堆,但是都是在BeanDefinition创建阶段做的时候,这个时候还没有进行bean的实例化,也就说明我们讲的拦截方法并没有没调用,真正调用肯定是在bean被实例化的时候。
其实这个
ImportAwareBeanPostProcessor很简单,就是调用EnhancedConfiguration接口的实现类中的setBeanFactory方法设置beanFactory对象,因为EnhancedConfiguration接口继承了BeanFactoryAware接口。
private static class ImportAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {
private final BeanFactory beanFactory;
public ImportAwareBeanPostProcessor(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
// Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's
// postProcessPropertyValues method attempts to autowire other configuration beans.
if (bean instanceof EnhancedConfiguration) {
((EnhancedConfiguration) bean).setBeanFactory(this.beanFactory);
}
return pvs;
}
...
}而
ImportAwareBeanPostProcessor的postProcessPropertyValues执行时机是在bean进行属性注入的时候。
