問題:在Spring Boot里面,怎么獲取定義在application.properties文件里的值、
我想訪問application.properties里面提供的值,像這樣:
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.loguserBucket.path=${HOME}/bucket
我想要在spring boot的主程序里訪問userBucket.path
回答一
Another way is injecting org.springframework.core.env.Environment to your bean.
另一種方法就把org.springframework.core.env.Environment
注入到你的bean里面
@Autowired
private Environment env;
....public void method() {..... String path = env.getProperty("userBucket.path");.....
}
回答二
@ConfigurationProperties
可以用于將.properties( .yml也行)的值映射到一個POJO
Consider the following Example file.
看一下下面的實例文件
.properties
cust.data.employee.name=Sachin
cust.data.employee.dept=Cricket
Employee.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;@ConfigurationProperties(prefix = "cust.data.employee")
@Configuration("employeeProperties")
public class Employee {private String name;private String dept;//Getters and Setters go here
}
Now the properties value can be accessed by autowiring employeeProperties as follows.
現在properties里面的值可以通過像下面那樣@Autowired一個employeeProperties,從而被訪問到。
@Autowired
private Employee employeeProperties;public void method() {String employeeName = employeeProperties.getName();String employeeDept = employeeProperties.getDept();}
回答三
你也可以這樣做
@Component
@PropertySource("classpath:application.properties")
public class ConfigProperties {@Autowiredprivate Environment env;public String getConfigValue(String configKey){return env.getProperty(configKey);}
}
無論你想怎么樣讀取application.properties,只要傳遞個key給getConfigValue方法就完事了
@Autowired
ConfigProperties configProp;// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port");
回答四
follow these steps. 1:- create your configuration class like below you can see
按這些步驟干:1. 創建你的 configuration類,像你下面看到的那樣
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;@Configuration
public class YourConfiguration{// passing the key which you set in application.properties@Value("${userBucket.path}")private String userBucket;// getting the value from that key which you set in application.properties@Beanpublic String getUserBucketPath() {return userBucket;}
}
- 當你有了一個configuration 類以后,就可以從configuration,注入你需要的變量了
@Component
public class YourService {@Autowiredprivate String getUserBucketPath;// now you have a value in getUserBucketPath varibale automatically.
}
文章翻譯自Stack Overflow:https://stackoverflow.com/questions/30528255/how-to-access-a-value-defined-in-the-application-properties-file-in-spring-boot