您的位置:首页 > 移动开发

spring-boot读取application配置文件中字段

2016-07-27 00:00 1211 查看
摘要: 如何更优雅的读取spring-boot读取application配置文件中字段

配置文件为application.properties

app-interface.url=http://192.168.2.179:8080/v1/


目的:读取 app-interface的url属性

使用@ConfigurationProperties来注入配置参数

在AppApplication.java中的配置

@EnableConfigurationProperties({AppInterface.class})
@SpringBootApplication
public class AppServerApplication {

public static void main(String[] args) {
SpringApplication.run(AppServerApplication.class, args);
}
}

AppInterface类中的配置

@Component
@ConfigurationProperties(prefix = "app-interface")
public class AppInterface {
// 暂时不支持
public static String url;
//  ="http://192.168.2.179:8080/v1/";

public static String getUrl() {
return url;
}

public static void setUrl(String url) {
AppInterface.url = url;
}

public AppInterface() {
}

}


本类中所有的字段值都可从application.properties中前缀为app-interface的属性中获取;

使用

1.可以直接使用AppInterface.url使用
2.可以@Autowired AppInterface appInterface;将AppInterface注入使用

版本问题

在 spring-boot 0.2.0-SNAPSHOT版中,Application.java中的@EnableConfigurationProperties({AppInterface.class}) 注解可不加,但AppInterface必须注册成bean

在 spring-boot 1.3.3中,AppInterface无须注册成bean,但必须在配置类中加入@EnableConfigurationProperties({AppInterface.class}) 注解;

使用@Value("${protpertName}")来注入配置参数

@Component
public class BlogProperties {

@Value("${app-interface.url}")
private String appUrl;
//省略get,set方法和构造器
}

这种方法比较简单,适合单个属性值的注入
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息