SpringBoot自定义Yaml加载器YamlLoader

场景和动机

本文中说的SpringBoot版本为1.3.5 - 1.3.8,都会出现这个问题,其他版本未做测试。

在SpringBoot框架中,接入第三方框架的时候,发现,配置placeholder出现问题,

<bean id="yamlProperties" class="org.springframework.beans.factory.config.YamlPropertiesFactoryBean">
    <property name="resources" value="classpath:conf/application*.yaml"/>
    </bean>

    <context:property-placeholder order="1" properties-ref="yamlProperties" ignore-unresolvable="true"/>

单独这种配置是没有问题的,但是这会导致Spring创建一个PropertySourcePlaceholderConfigurer。
假如其他的框架 也注册了这个,下面称作Bean.

有两个的情况下,SpringBoot启动时,可能会遇到如下问题:

  • 在创建Bean的过程中,处理PropertySource的时候,会找不到自定义配置
  • 即使调整了优先级,某些Bean注入成功,还会遇到框架内部使用了Autoconfiguration的组建启动失败。

注意这里的配置文件路径 /conf/ 而不是 /config/,没有上述配置,Spring加载不到这里的配置文件。
举例:

  • 假如里面配置了Datasource的连接信息,则可能导致Datasource 配置类注入失败。(第一个注册的Bean找不到这里的配置,调整优先级使得xml中配置的Bean在前面,则注入成功)
  • 假如里面配置了SpringCloud的Eureka的注册中心地址,则SpringCloud启动Eureka失败。(上面调整过Order也无法成功启动Eureka)原因如下:
//ConfigurationPropertiesBindingPostProcessor.java

private PropertySourcesPlaceholderConfigurer getSinglePropertySourcesPlaceholderConfigurer() {
        // Take care not to cause early instantiation of all FactoryBeans
        if (this.beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) this.beanFactory;
            Map<String, PropertySourcesPlaceholderConfigurer> beans = listableBeanFactory
                    .getBeansOfType(PropertySourcesPlaceholderConfigurer.class, false,
                            false);
            if (beans.size() == 1) {
                return beans.values().iterator().next();
            }
        }
        return null;
    }

如果发现有两个,则return null。那么可以看出,Spring的建议是这个Bean只需要创建一个。

因此需要写一个自定义Loader,并且删掉上述Bean的XML配置

直接上代码

//自定义YamlLoader

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import java.util.Map;

@Slf4j
public class YamlPropertiesLoader implements SpringApplicationRunListener, Ordered {

    private YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

    public YamlPropertiesLoader(SpringApplication application, String[] args) {
        //ignore
    }

    @Override
    public void started() {

    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {

    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        try {
            Resource[] resources = context.getResources("classpath:conf/application*.yaml");

            String[] activeProfiles = context.getEnvironment().getActiveProfiles();
            if (activeProfiles == null || activeProfiles.length == 0) {
                return;
            }

            log.info("Detect the Active profiles are {}", StringUtils.arrayToCommaDelimitedString(activeProfiles));
            MutablePropertySources propertySources = context.getEnvironment().getPropertySources();

            Map<String, Resource> resourceMap = Maps.newHashMap();
            for (Resource resource : resources) {
                String filename = resource.getFilename();
                int startCut = filename.lastIndexOf("-") + 1;
                String env = filename.substring(startCut, filename.length() - 5);
                resourceMap.put(env, resource);
            }

            for (String activeProfile : activeProfiles) {
                Resource resource = resourceMap.get(activeProfile);
                if (resource == null) {
                    throw new IllegalStateException("Fail to load profile [" + activeProfile + "]");
                }
                PropertySource<?> load = loader.load("YamlProperties", resource, null);//Point
                if (load == null) {
                    log.error("Properties Load From YAML Fail");
                    return;
                }
                propertySources.addLast(load);
            }
        } catch (Exception e) {
            throw new IllegalStateException(
                    "Failed to load yaml configuration", e);
        }
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {

    }

    @Override
    public void finished(ConfigurableApplicationContext context, Throwable exception) {

    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 1;
    }
}

解释

loader.load("YamlProperties", resource, null);//Point
这处代码第三个参数为profile,但这里传入null??

在我写这个加载器的时候,发现profile如果传了真正的profile时,结果是null。
最后追查发现,是因为配置文件里面的yaml并非真正的yaml语法,而是yml语法。推测是因为这个原因导致 匹配不到给定的Profile,因此指定null。

拓展

为什么要写这么复杂的步骤,假如真的需要某些特殊操作真的要自己定义加载器,例如加密等等,这就很有用了。

但是我并不需要加密等特殊操作。

于是,有一个更简单的方法,那就是
把配置文件的路径改到 /config 下,这是SpringBoot默认一定会加载的位置。

完。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。