javascript
在Spring Boot里面,怎么获取定义在application.properties文件里的值
問題:在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里面
回答二
@ConfigurationProperties可以用于將.properties( .yml也行)的值映射到一個(gè)POJO
Consider the following Example file.
看一下下面的實(shí)例文件
.properties
cust.data.employee.name=Sachin cust.data.employee.dept=CricketEmployee.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.現(xiàn)在properties里面的值可以通過像下面那樣@Autowired一個(gè)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,只要傳遞個(gè)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. 創(chuàng)建你的 configuration類,像你下面看到的那樣
文章翻譯自Stack Overflow:https://stackoverflow.com/questions/30528255/how-to-access-a-value-defined-in-the-application-properties-file-in-spring-boot
總結(jié)
以上是生活随笔為你收集整理的在Spring Boot里面,怎么获取定义在application.properties文件里的值的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到有人被杀了有什么兆头
- 下一篇: 梦到自己生孩子喂奶是什么意思