手机版 欢迎访问it开发者社区(www.mfbz.cn)网站

当前位置: > 开发

Spring @Configuration如何注入

时间:2021/5/29 21:54:45|来源:|点击: 次

业务代码一般用拦截器拦截注解,并作相应定义。但Spring的注解如@Conguration是通过XxxxPostProcessor来进行注入。
 
@Configuration有独属的postProcessor处理器 - ConfigurationClassPostProcessor
 
@Configuration作用及使用案例
作用:类型以前的XML配置注入对应的Bean,将比如application.properties的属性注入到对应的Bean实体类
 
使用案例(比如下面就将xxl.job.xx的配置通过@Value注入进来,并且生成XxlJobSpringExecutor的Bean):
@Configuration
public class XxlJobConfig {
    private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);
    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;
    @Value("${xxl.job.accessToken}")
    private String accessToken;
    @Value("${xxl.job.executor.appname}")
    private String appname;
    @Value("${xxl.job.executor.address}")
    private String address;
    @Value("${xxl.job.executor.ip}")
    private String ip;
    @Value("${xxl.job.executor.port}")
    private int port;
    @Value("${xxl.job.executor.logpath}")
    private String logPath;
    @Value("${xxl.job.executor.logretentiondays}")
    private int logRetentionDays;
 
    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
        xxlJobSpringExecutor.setAppname(appname);
        xxlJobSpringExecutor.setAddress(address);
        xxlJobSpringExecutor.setIp(ip);
        xxlJobSpringExecutor.setPort(port);
        xxlJobSpringExecutor.setAccessToken(accessToken);
        xxlJobSpringExecutor.setLogPath(logPath);
        xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
        return xxlJobSpringExecutor;
    }
}
 
ConfigurationClassPostProcessor注入注解@Conguration的过程
1 ConfigurationClassPostProcessor实现了BeanDefinitionRegistryPostProcessor,会调用postProcessBeanDefinitionRegistry()来注册baen
 
2 postProcessBeanDefinitionRegistry()调用this.processConfigBeanDefinitions(registry)
-- 2.1 从BeanDefinitionRegistry中筛选出配置类
-- 2.2 对配置类的BeanDefinition进行解析,并注册Bean
 
@Conguration解析过程如下
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
    List<BeanDefinitionHolder> configCandidates = new ArrayList<>();// 候选配置类集合
    String[] candidateNames = registry.getBeanDefinitionNames();// 获取所有的BeanDefinition的name数组
 
    for (String beanName : candidateNames) {
        BeanDefinition beanDef = registry.getBeanDefinition(beanName);
        // 如果BeanDefinition中有这个属性存在,说明作为一个配置类已经被处理过了
        if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
            }
        // 检查是否为一个配置类 
                        // 查看是否具有@Configuration注解 
                        // 这里不会仅仅看BeanDefinition所代表的类直接标注的注解,而是会递归查找其注解的注解是否有为 
                        // @Configuration,只要找到了那么当前的类就是一个配置类
        } else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
            configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
        }
    }
 
    // Return immediately if no @Configuration classes were found
    if (configCandidates.isEmpty()) {// 如果一个@Configuration都没有直接终止
        return;
    }
 
    // Sort by previously determined @Order value, if applicable
    configCandidates.sort((bd1, bd2) -> {// 找到@Order注解里面的值排序,明显是升序,@Order(N),N越小权重越大
        int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
        int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
        return Integer.compare(i1, i2);
    });
 
    // Detect any custom bean name generation strategy supplied through the enclosing application context
    SingletonBeanRegistry sbr = null;
    if (registry instanceof SingletonBeanRegistry) {// 如果有自定义Bean Name生成器,就使用自定义的
        sbr = (SingletonBeanRegistry) registry;
        if (!this.localBeanNameGeneratorSet) {
            BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
                AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
            if (generator != null) {
                this.componentScanBeanNameGenerator = generator;
                this.importBeanNameGenerator = generator;
            }
        }
    }
 
    if (this.environment == null) {// 如果还没有初始化Environment对象,初始化一个
        this.environment = new StandardEnvironment();
    }
 
    // Parse each @Configuration class // 解析每一个被@Configuratin标注的注解类
    ConfigurationClassParser parser = new ConfigurationClassParser(
        this.metadataReaderFactory, this.problemReporter, this.environment,
        this.resourceLoader, this.componentScanBeanNameGenerator, registry);
 
    Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
    Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
    do {
        StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");
        parser.parse(candidates);
        parser.validate();
 
        Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
        configClasses.removeAll(alreadyParsed);
 
        // Read the model and create bean definitions based on its content
        if (this.reader == null) {// 构造一个BeanDefinitionReader
            this.reader = new ConfigurationClassBeanDefinitionReader(
                registry, this.sourceExtractor, this.resourceLoader, this.environment,
                this.importBeanNameGenerator, parser.getImportRegistry());
        }
        this.reader.loadBeanDefinitions(configClasses);// 加载配置类中的@Bean,生成BeanDefinition
        alreadyParsed.addAll(configClasses);
        processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();
 
        candidates.clear();// 清除
        // 考虑到@Import进来的或者@ImportSource或者@Bean等方式注入进来的会有配置类
                      // 比如@Bean判断为:ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)
                        //                                            ->isConfigurationCandidate
                        //                                         ->P166行 metadata.hasAnnotatedMethods(Bean.class.getName())
        if (registry.getBeanDefinitionCount() > candidateNames.length) {
            String[] newCandidateNames = registry.getBeanDefinitionNames();
            Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
            Set<String> alreadyParsedClasses = new HashSet<>();
            for (ConfigurationClass configurationClass : alreadyParsed) {
                alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
            }
            for (String candidateName : newCandidateNames) {
                if (!oldCandidateNames.contains(candidateName)) {
                    BeanDefinition bd = registry.getBeanDefinition(candidateName);
                    if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
                        !alreadyParsedClasses.contains(bd.getBeanClassName())) {
                        candidates.add(new BeanDefinitionHolder(bd, candidateName));
                    }
                }
            }
            candidateNames = newCandidateNames;
        }
    } while (!candidates.isEmpty());
 
    // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
    // 把 ImportRegistry注册成一个Bean,以便支持 继承ImportAware 有注解类@Configuration的配置类
    if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
        sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
    }
    
    if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
        // Clear cache in externally provided MetadataReaderFactory; this is a no-op
        // for a shared cache since it'll be cleared by the ApplicationContext.
        ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
    }
}
 
 
 
 
 
 
 
 
 
 
 
 

Copyright © 2002-2019 某某自媒体运营 版权所有