使用@PropertySource动态加载不同环境的配置文件

1,325 阅读1分钟

前言

自定义配置文件是我们日常开发中经常会使用的资源,而spring只提供了类似application-* 的这中匹配方式,并不支持我们自定义的配置文件名称,例如:customize-dev.properties,但是spring提供了一个注解可以方便加载我们的自定义配置文件,它就是@PropertySource

自定义配置文件

customize-dev.properties

customize.name=dev

使用@PropertySource加载配置文件

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
​
@Data
@Component
@PropertySource(value = "classpath:customize${customize.profiles.active:}.properties")
@ConfigurationProperties(prefix = "customize", ignoreInvalidFields = true)
public class Customize {
    private String name;
}

指定配置文件

-Dcustomize.profiles.active=-dev

启动测试

import com.learning.shiro.config.Customize;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
​
import javax.annotation.Resource;
​
@RestController
@Slf4j
public class CustomizeController {
    @Resource
    private Customize customize;
​
    @RequestMapping(value = "/")
    public ResponseEntity<?> index() {
        return new ResponseEntity<Customize>(customize, HttpStatus.OK);
    }
}

结果

{
    name: "dev"
}

扩展

以上的方式只能加载一个配置文件而且不是很优雅,可以通过实现PropertySourceFactory自定义加载配置文件,但是这种方式本人没有尝试过,有尝试过的朋友可以分享一下自己的实现方案。

import java.io.IOException;
import org.springframework.core.env.PropertySource;
import org.springframework.lang.Nullable;
​
public class DefaultPropertySourceFactory implements PropertySourceFactory {
    public DefaultPropertySourceFactory() {
    }
​
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
    }
}

DefaultPropertySourceFactory 是官方提供的默认的配置文件加载方式,大家可以根据业务自定义实现自己的加载方式。

总结

以上就是本片文章的全部内容,主要介绍了@PropertySoure注解的基本使用,如果有更好的方案,欢迎大家讨论分析,感谢。