Spring boot 加载自定义配置(写给自己以后看)

2017-03-20  本文已影响499人  else05

文章是写给自己以后看的

# 在xxx.properties中
accessToken=JXEbQ1l2
serviceUrl=http://127.0.0.1:8080
# 在xxx.yaml中
accessToken: JXEbQ1l2
serviceUrl: http://127.0.0.1:8080
    @Value("${accessToken}")
    private String              accessToken;
    @Value("${serviceUrl}")
    private String              serviceUrl;
// 在spring主方法上加上注解@PropertySource
@PropertySource("classpath:config/config.properties")
@SpringBootApplication
public class DataShareClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(DataShareClientApplication.class, args);
    }
}
// 然后就可以使用@Value取值
public class Processor {
    @Value("${accessToken}")
    private String              accessToken;
    @Value("${serviceUrl}")
    private String              serviceUrl;
}

注:如果配置文件在jar包的外面,没有打包在jar包里面,可以试一下使用@PropertySource("${user.dir}/xxx.properties") 加载。

以上的方式比较好用 , 还可以使用Environment 和 @ConfigurationProperties的方式,具体操作看下面的参考文章

参考:

上一篇 下一篇

猜你喜欢

热点阅读