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注入使用java

版本问题

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

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

相关文章
相关标签/搜索