springboot加載自定義properties原理

springboot自定義屬性文件通過value注解引入昆咽,和@autowired不同的是,它是由ConfigurationClassPostProcessor這個BeanDefinitionRegistryPostProcessor來處理调违,屬性文件的讀取和注入是在BeanDefinition級別技肩,對象實例化之前浮声。

我們建一個簡單的類的梳理一下。

@Component
@Data
@PropertySource(name="myprod",value = "classpath:config/product.properties")
public class Product {
    @Value("${prod.name}")
    private String name;
    @Value("${product.title}")
    private String title;
}
image.png

調用堆棧 從refresh開始,主要走了這幾個方法:
invokeBeanFactoryPostProcessors
invokeBeanDefinitionRegistryPostProcessors
ConfigurationClassPostProcessor->processConfigBeanDefinitions
ConfigurationClassParser->doProcessConfigurationClass
ConfigurationClassParser->processPropertySource
ConfigurationClassParser->addPropertySource

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
        List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
        String[] candidateNames = registry.getBeanDefinitionNames();

        for (String beanName : candidateNames) {
            BeanDefinition beanDef = registry.getBeanDefinition(beanName);
            if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
                    ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
                }
            }"代碼會走這里因為com.timmy.app沒有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()) {
            return;
        }


        "這個就是用來處理各種配置類的parser"
        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 {  "開始解析主類com.timmy.app的bean定義了"
            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) {
                this.reader = new ConfigurationClassBeanDefinitionReader(
                        registry, this.sourceExtractor, this.resourceLoader, this.environment,
                        this.importBeanNameGenerator, parser.getImportRegistry());
            }
           "準備解析@Configuration標簽的配置類辛蚊,就是之前忽略的"
            this.reader.loadBeanDefinitions(configClasses);
            alreadyParsed.addAll(configClasses);

           省略代碼...

ConfigurationClassParser主要方法:
doProcessConfigurationClass->processPropertySource->addPropertySource

邏輯主要集中在doProcessConfigurationClass方法
doProcessConfigurationClass負責解析@PropertySource袋马,@Import annotations秸应,@ComponentScan等注解 软啼。
1 調用processPropertySource處理自身的propertySource
2 掃描類上的ComponentScan,對掃出的類繼續(xù)調用parse
3 處理@Import annotations等其他標簽


    protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
            throws IOException {

        if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
            // Recursively process any member (nested) classes first
            processMemberClasses(configClass, sourceClass);
        }

        "處理sourceClass上的@PropertySource注解"锣披,
        for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
                sourceClass.getMetadata(), PropertySources.class,
                org.springframework.context.annotation.PropertySource.class)) {
            if (this.environment instanceof ConfigurableEnvironment) {
                processPropertySource(propertySource);
            }
            else {
                logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
                        "]. Reason: Environment must implement ConfigurableEnvironment");
            }
        }

        "掃描sourceClass上@ComponentScan下所有類,繼續(xù)parse "      
        Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
                sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
        if (!componentScans.isEmpty() &&
                !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
            for (AnnotationAttributes componentScan : componentScans) {
                // The config class is annotated with @ComponentScan -> perform the scan immediately
                Set<BeanDefinitionHolder> scannedBeanDefinitions =
                        this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
                // Check the set of scanned definitions for any further config classes and parse recursively if needed
                for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
                    BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
                    if (bdCand == null) {
                        bdCand = holder.getBeanDefinition();
                    }
                    if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
                    "開始解析每個掃出的類"                    
                        parse(bdCand.getBeanClassName(), holder.getBeanName());
                    }
                }
            }
        }

        // Process any @Import annotations
        processImports(configClass, sourceClass, getImports(sourceClass), true);

        // Process any @ImportResource annotations
        AnnotationAttributes importResource =
                AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
        if (importResource != null) {
            String[] resources = importResource.getStringArray("locations");
            Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
            for (String resource : resources) {
                String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
                configClass.addImportedResource(resolvedResource, readerClass);
            }
        }

        // Process individual @Bean methods
        Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
        for (MethodMetadata methodMetadata : beanMethods) {
            configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
        }

        // Process default methods on interfaces
        processInterfaces(configClass, sourceClass);

        // Process superclass, if any
        if (sourceClass.getMetadata().hasSuperClass()) {
            String superclass = sourceClass.getMetadata().getSuperClassName();
            if (superclass != null && !superclass.startsWith("java") &&
                    !this.knownSuperclasses.containsKey(superclass)) {
                this.knownSuperclasses.put(superclass, configClass);
                // Superclass found, return its annotation metadata and recurse
                return sourceClass.getSuperClass();
            }
        }

        // No superclass -> processing is complete
        return null;
    }

processPropertySource結構很簡單:
1根據(jù)注解里的location屬性載入配置文件
2調用addPropertySource處理每個屬性文件

private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
        String name = propertySource.getString("name");
        if (!StringUtils.hasLength(name)) {
            name = null;
        }
        String encoding = propertySource.getString("encoding");
        if (!StringUtils.hasLength(encoding)) {
            encoding = null;
        }
        String[] locations = propertySource.getStringArray("value");
        Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
        boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

        Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
        PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
                DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));

        for (String location : locations) {
            try {
                String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
                Resource resource = this.resourceLoader.getResource(resolvedLocation);
                addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
            }
            catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
                // Placeholders not resolvable or resource not found when trying to open it
                if (ignoreResourceNotFound) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
                    }
                }
                else {
                    throw ex;
                }
            }
        }
    }

addPropertySource這個類才是真正處理@value屬性:
1把用戶定義的properties文件加到Eniverment中去
2如果有相同name的屬性文件胧辽,需要合并


private void addPropertySource(PropertySource<?> propertySource) {
        String name = propertySource.getName();
        MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
        if (this.propertySourceNames.contains(name)) {
            // 可能會有多個地方注解同一個屬性文件邑商,
            PropertySource<?> existing = propertySources.get(name);
            if (existing != null) {
                PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
                        ((ResourcePropertySource) propertySource).withResourceName() : propertySource);
                if (existing instanceof CompositePropertySource) {
                    ((CompositePropertySource) existing).addFirstPropertySource(newSource);
                }
                else {
                    if (existing instanceof ResourcePropertySource) {
                        existing = ((ResourcePropertySource) existing).withResourceName();
                    }
                    CompositePropertySource composite = new CompositePropertySource(name);
                    composite.addPropertySource(newSource);
                    composite.addPropertySource(existing);
                    propertySources.replace(name, composite);
                }
                return;
            }
        }

        if (this.propertySourceNames.isEmpty()) {
            propertySources.addLast(propertySource);
        }
        else {
            String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
            propertySources.addBefore(firstProcessed, propertySource);
        }
        this.propertySourceNames.add(name);
    }
    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        return (name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource));
    }

CompositePropertySource 的場景其實是你有兩個不同的文件人断,但是 @PropertySource中設置同樣的name屬性,這樣CompositePropertySource 會做一個合并影锈,按加入的時間順序取蝉绷。

增加一個product2,PropertySource name都設置為myprod

@Component
@Data
@PropertySource(name="myprod",value = "classpath:config/product.properties")
public class Product {
    @Value("${prod.name}")
    private String name;
    @Value("${product.title}")
    private String title;
}


@Component
@Data
@PropertySource(name="myprod",value = "classpath:config/product2.properties")
public class Product2 {
    @Value("${prod.name}")
    private String name;
    @Value("${product.title}")
    private String title;
}

debug到addPropertySource辆床,newSource和existing已經不一樣了讼载。
environment的propertySources里也有兩份文件了中跌。

image.png
image.png
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末漩符,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子凸克,更是在濱河造成了極大的恐慌闷沥,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件戳粒,死亡現(xiàn)場離奇詭異鸟雏,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進店門又活,熙熙樓的掌柜王于貴愁眉苦臉地迎上來锰悼,“玉大人,你說我怎么就攤上這事耐薯∷坷铮” “怎么了?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵臼婆,是天一觀的道長幌绍。 經常有香客問我傀广,道長,這世上最難降的妖魔是什么伪冰? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任糜值,我火速辦了婚禮,結果婚禮上病往,老公的妹妹穿的比我還像新娘骄瓣。我一直安慰自己,他們只是感情好畔勤,可當我...
    茶點故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布庆揪。 她就那樣靜靜地躺著,像睡著了一般缸榛。 火紅的嫁衣襯著肌膚如雪内颗。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天恨溜,我揣著相機與錄音找前,去河邊找鬼。 笑死系吭,一個胖子當著我的面吹牛颗品,可吹牛的內容都是我干的。 我是一名探鬼主播则吟,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼氓仲,長吁一口氣:“原來是場噩夢啊……” “哼得糜!你這毒婦竟也來了?” 一聲冷哼從身側響起朝抖,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤治宣,失蹤者是張志新(化名)和其女友劉穎砌滞,沒想到半個月后坏怪,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體铝宵,經...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了拼岳。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片况芒。...
    茶點故事閱讀 39,953評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡绝骚,死狀恐怖,靈堂內的尸體忽然破棺而出粪牲,到底是詐尸還是另有隱情止剖,我是刑警寧澤,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布亭引,位于F島的核電站皮获,受9級特大地震影響洒宝,放射性物質發(fā)生泄漏。R本人自食惡果不足惜雁歌,卻給世界環(huán)境...
    茶點故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一将宪、第九天 我趴在偏房一處隱蔽的房頂上張望橡庞。 院中可真熱鬧印蔗,春花似錦、人聲如沸吧趣。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至八匠,卻和暖如春趴酣,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背岖寞。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工仗谆, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人厌处。 一個月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓阔涉,卻偏偏與公主長得像捷绒,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子暖侨,可洞房花燭夜當晚...
    茶點故事閱讀 44,901評論 2 355

推薦閱讀更多精彩內容