问题:在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