1. 程式人生 > 其它 >springboot 讀取配置資訊

springboot 讀取配置資訊

Spring Boot可以通過 @PropertySource, @Value, @Environment, @ConfigurationProperties 來繫結變數

1.讀取application檔案

key.value=123456
key.password=123456

  @Value註解讀取

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ToolsConfilg{

  @Value(
"${key.value}")
private String value;
@Value(
"${key.password}")
private String password;

//...GET\SET
}

  @ConfigurationProperties註解讀取

@Component
@ConfigurationProperties(prefix = "info") public class ToolsConfilg{
private String key;
private String password;

//...GET\SET
}

  讀取指定檔案

  在resources(資源目錄)下建立 config/datasource-config.properties

datasource.username=root

datasource.password=root

  @PropertySource+@Value註解讀取 (@PropertySource不支援yml檔案讀取)

@Component
@PropertySource(value = { "config/datasource-config.properties" })
public class DatasourceConfig{
 @Value("${datasource.username}")
 
private String username; @Value("${datasource.password}") private String password; public String getUsername() {
  ....get/set
}

  @PropertySource+@ConfigurationProperties註解讀取

@Component
@ConfigurationProperties(prefix = "datasource")
@PropertySource(value = { "config/datasource-config.properties" })
public class DatasourceConfig{
 private String username;
 private String password;
 
  ...get/set
}

  Environment讀取

@Autowired
private Environment env;
// 獲取引數
String getProperty(String key);