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方法和构造器
    }

这种方法比较简单,适合单个属性值的注入

转载于:https://my.oschina.net/u/1590027/blog/718990

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值