spring-boot读取application配置文件中字段
2016-07-27 00:00
1211 查看
摘要: 如何更优雅的读取spring-boot读取application配置文件中字段
目的:读取 app-interface的url属性
本类中所有的字段值都可从application.properties中前缀为app-interface的属性中获取;
2.可以@Autowired AppInterface appInterface;将AppInterface注入使用
在 spring-boot 1.3.3中,AppInterface无须注册成bean,但必须在配置类中加入@EnableConfigurationProperties({AppInterface.class}) 注解;
这种方法比较简单,适合单个属性值的注入
配置文件为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方法和构造器 }
这种方法比较简单,适合单个属性值的注入
相关文章推荐
- redis的导入导出需要特别注意的地方
- 使用C#实现读取系统配置文件的代码实例讲解
- Powershell Profiles配置文件的存放位置介绍
- PowerShell入门教程之创建和使用配置文件实例
- SERV-U 的配置文件详解
- php.ini 配置文件的深入解析
- redis2.8配置文件中文翻译版
- PHP配置文件php.ini中打开错误报告的设置方法
- C#中读取App.config配置文件代码实例
- c++实现逐行读取配置文件写入内存的示例
- 关于session在PHP5的配置文件中的详细设置参数说明
- MySQL 配置文件my.cnf 例子最详细翻译
- apache 配置文件解说
- Android 读取Properties配置文件的小例子
- PHP 配置文件中open_basedir选项作用
- .net 读取非标准配置文件的小例子
- APACHE 配置文件中文版 httpd.conf FOR Apache 2.2.13
- 读取spring配置文件的方法(spring读取资源文件)
- PHPMyadmin 配置文件详解(配置)
- C# WinForm开发中使用XML配置文件实例