@Configuration 中使用构造函数与@Autowired 无法注入的踩坑经历

1.问题描述

@Configuration
@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceConfig {

    private DataSourceProperties dataSourceProperties;

    @Autowired
    public void setSiheDataSourceProperties(DataSourceProperties DataSourceProperties) {
        this.DataSourceProperties = dataSourceProperties;
    }



    @Bean(name = "dataSourceMaster")
    public DataSource masterDataSource() {

        return new DruidDataSource();
    }

    @Bean(name = "sqlScannerConfigurer")
    public BeetlSqlScannerConfigurer getBeetlSqlScannerConfigurer() {
        BeetlSqlScannerConfigurer conf = new BeetlSqlScannerConfigurer();
        conf.setBasePackage("com.xx..dao");
        conf.setDaoSuffix("Dao");
        conf.setSqlManagerFactoryBeanName("sqlManagerFactoryBean");
        return conf;
    }
}

在使用alibaba Druid 时,由于配置文件的复杂性,所以使用了EnableConfigurationProperties 来制定配置类,但运行时始终发现无法注入;获得的dataSourceProperties始终为空;

2.问题出现原因分析

查阅各种资料,最终在spring官网的docs(Composing Java-based Configurations :: Spring Framework)中发现以下说明

注意到了

Also, be particularly careful with BeanPostProcessor and BeanFactoryPostProcessor definitions through @Bean. Those should usually be declared as static @Bean methods, not triggering the instantiation of their containing configuration class. Otherwise, @Autowired and @Value may not work on the configuration class itself, since it is possible to create it as a bean instance earlier than AutowiredAnnotationBeanPostProcessor.

大致意思就是

@Configuration 和其要声明的@Bean,要注意BeanPostProcessorBeanFactoryPostProcessor的定义,否则@Autowired和@Value 无法正常工作;于是在申明的bean中发现BeetlSqlScannerConfigurer果然实现了BeanDefinitionRegistryPostProcessor,在注释掉该bean的声明果然可以使用@Autowired和构造方法的注入;

public class BeetlSqlScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware, BeanNameAware {
    protected String basePackage;
    protected String daoSuffix = "Dao";
    protected ApplicationContext applicationContext;
    protected String beanName;
    protected BeanNameGenerator nameGenerator;
    protected String sqlManagerFactoryBeanName;

3.刨根问底

作为一个程序员必须认一下这个死理,接下来是代码环节;

Spring 容器启动流程中的关键步骤和类

1.AbstractApplicationContext#refresh()

@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // 预处理
        prepareRefresh();

        // 告诉子类刷新内部bean工厂。
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // 准备bean工厂绑定到上下文
        prepareBeanFactory(beanFactory);
        try {
      
            postProcessBeanFactory(beanFactory);
            
            invokeBeanFactoryPostProcessors(beanFactory);

            registerBeanPostProcessors(beanFactory);

           
        }
        catch (BeansException ex) {
           //其余省略
        }
    }
}

2.AbstractApplicationContext#invokeBeanFactoryPostProcessors()

调用所有注册的 BeanFactoryPostProcessor,包括 BeanDefinitionRegistryPostProcessor

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
}

3.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()

识别并调用 BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessor。

public static void invokeBeanFactoryPostProcessors(
        ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

   
    List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

        invokeBeanDefinitionRegistryPostProcessors(registryProcessors, registry);
    }

   
    invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}

这个会调用到ConfigurationClassPostProcessor#postProcessBeanFactory()

4.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors

这这个方法是整个执行流程的入口点,用于调用所有注册的 BeanFactoryPostProcessorBeanDefinitionRegistryPostProcessor

public static void invokeBeanFactoryPostProcessors(
        ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

    // 1. 首先执行 BeanDefinitionRegistryPostProcessor
    Set<String> processedBeans = new HashSet<>();

    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

        // 找到所有 BeanDefinitionRegistryPostProcessor 类型的 bean
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

        for (String ppName : postProcessorNames) {
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                registryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));//注意这句!!!!!!!
                processedBeans.add(ppName);
            }
        }

        // 按照 PriorityOrdered 执行
        sortPostProcessors(registryProcessors, beanFactory);
        invokeBeanDefinitionRegistryPostProcessors(registryProcessors, registry);

        // Clear the list and gather all BeanDefinitionRegistryPostProcessor beans.
        registryProcessors.clear();

        // This step will instantiate and invoke BeanDefinitionRegistryPostProcessor
        // of Ordered priority next
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

        for (String ppName : postProcessorNames) {
            if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                registryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }

        // 按照 Ordered 执行
        sortPostProcessors(registryProcessors, beanFactory);
        invokeBeanDefinitionRegistryPostProcessors(registryProcessors, registry);
        registryProcessors.clear();

        // 其他 BeanDefinitionRegistryPostProcessor
        boolean reiterate = true;
        while (reiterate) {
            reiterate = false;
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName)) {
                    registryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                    reiterate = true;
                }
            }
            sortPostProcessors(registryProcessors, beanFactory);
            invokeBeanDefinitionRegistryPostProcessors(registryProcessors, registry);
            registryProcessors.clear();
        }
    }

    // 2. 接着执行 BeanFactoryPostProcessor
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

    // 首先执行 PriorityOrdered 接口的 BeanFactoryPostProcessor
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
    for (String ppName : postProcessorNames) {
        if (processedBeans.contains(ppName)) {
            // Skip - already processed in first phase above
        } else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            orderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        }
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

    // 接下来执行 Ordered 接口的 BeanFactoryPostProcessor
    orderedPostProcessors.clear();
    for (String ppName : postProcessorNames) {
        if (processedBeans.contains(ppName)) {
            // Skip - already processed in first phase above
        } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        }
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

    // 最后执行普通的 BeanFactoryPostProcessor
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
    for (String ppName : postProcessorNames) {
        if (!processedBeans.contains(ppName)) {
            nonOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        }
    }
    invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
}

beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class) 负责实例化所有 BeanDefinitionRegistryPostProcessor 类型的 bean。如果这些 bean 是通过 @Bean 方法定义的,那么此时 Spring 就会调用该方法进行实例化。

Spring 的 BeanDefinitionRegistryPostProcessor 在所有 BeanFactoryPostProcessor 之前执行,任何实现或包含这种类型的 bean 的 @Bean 方法会在配置类的增强被代理之前被实例化。导致了配置类的 @Bean 方法可能没有被代理,而直接作为普通方法执行。

4.总结

BeanDefinitionRegistryPostProcessor 的特殊性,导致配置类的某些 @Bean 方法可能在增强之前被实例化,这会引起依赖注入的问题。 如果发现在@Configuration 无法注入检查所要声明的bean 是否有这种情况;

如果注入的是配置类,检查是否存在@Builder,使用了@Builder则会导致 该类的没有无参构造函数,会有全参构造函数,导致属性设置失败;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值