spring boot啟動載入外部配置檔案

workabee發表於2018-02-07

業務需求:載入外部配置檔案,部署時更改比較方便。

先上程式碼:

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplicationBuilder springApplicationBuilder = new SpringApplicationBuilder(Application.class);
        springApplicationBuilder.web(true);
        Properties properties = getProperties();
        StandardEnvironment environment = new StandardEnvironment();
        environment.getPropertySources().addLast(new PropertiesPropertySource("micro-service", properties));
        springApplicationBuilder.environment(environment);
        springApplicationBuilder.run(args);
    }

    private static Properties getProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        propertiesFactoryBean.setIgnoreResourceNotFound(true);
        Resource fileSystemResource = resolver.getResource("file:/opt/company/test.properties");
        propertiesFactoryBean.setLocations(fileSystemResource);
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }
}

使用變數的工具類

@Component
public class EnvironmentUtil {

    private static Environment environment;

    @Autowired
    public void setEnvironment(Environment environment) {
        EnvironmentUtil.environment = environment;
    }

    public static <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
        return environment.getProperty(key, targetType, defaultValue);
    }

    public static <T> T getProperty(String key, Class<T> targetType) {
        return environment.getProperty(key, targetType);
    }

    public static String getProperty(String key) {
        return environment.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        return environment.getProperty(key, defaultValue);
    }

    public static Integer getInteger(String key, Integer defaultValue) {
        return environment.getProperty(key, Integer.class, defaultValue);
    }
}

也可以通過@Value(“${key}”)使用

這中載入方法優先順序很高,如果與spring boot配置檔案同名,將覆蓋application.properties檔案中的配置。

更新:
工具類可能晚於某些初始化的類載入。請新增@DependsOn("environmentUtil")

相關文章