spring @Profiles和@PropertySource两种根据环境切换配置文件方式

使用@PropertySource注解加载配置文件,并制定解析配置文件的解析器默认是properties,可以自己指定使用Yml配置文件解析器。

@SpringBootApplication
@PropertySource(value = "classpath:config-${spring.profiles.active}.yml",
        encoding = "UTF-8",
        factory = YmlPropertySourceFactory.class)
public class Application {

    public static void main(String[] args) {
        try {
            SpringApplication.run(Application.class, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

resources下的需要一个全局配置文件application.yml(我使用的是yml格式配置文件),这个配置文件就是用来切换不同环境下的配置文件的,其他配置文件就根据环境做一个不同的后缀,config-dev.yml,config-pro.yml。

Yml格式配置文件的解析需要用下面方式切换一下。就是根据文件的后缀判断文件格式使用不同的配置文件加载器。

public class YmlPropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = name != null ? name : resource.getResource().getFilename();
        if (!resource.getResource().exists()) {
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }

    private Properties loadYml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

}

然后在公共配置文件application.yml中添加spring.profiles.active配置,值就是config-dev.yml中的dev或者pro。其实spring.profiles.active就是spring用来指定不同环境的,可以用@Profiles 和@ActiveProfiles注解来指定不同的配置文件,@Profiles注解在类或@bean注解的方法上可以实现不同的配置实例化不同的类,然后通过jvm参数来指定spring.profiles.active值就能做到运行切换配置环境了,jvm参数:

     JAVA_OPTS=" -Xms1024m -Xmx1024m  -XX:PermSize=512m -XX:MaxPermSize=512m -Dspring.profiles.active=dev"

上面我提供的方式是在配置文件中修改一个参数的值达到切换配置文件的目的,@Profiles注解的方式是用jvm参数的方式在启动时切换配置文件,可以根据情况选择。

你可能感兴趣的:(spring,boot,java)