问题
我想访问application.properties
中提供的值,例如:
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log
userBucket.path=${HOME}/bucket
我想在Spring Boot应用程序中访问我的主程序中的userBucket.path
。
#1 热门回答(192 赞)
你可以使用@Value
注释并在你正在使用的任何Spring bean中访问该属性
@Value("${userBucket.path}")
private String userBucketPath;
Spring Boot文档的Externalized Configuration部分解释了你可能需要的所有细节。
#2 热门回答(118 赞)
另一种方法是向你的bean注入Environment。
@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.path");
.....
}
#3 热门回答(6 赞)
@ConfigurationProperties
可用于将值从.properties
(支持.yml
)映射到POJO。
请考虑以下示例文件。
.properties
cust.data.employee.name=Sachin
cust.data.employee.dept=Cricket
585841157 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
}
现在可以通过autowiringemployeeProperties
访问属性值。
@Autowired
private Employee employeeProperties;
public void method() {
String employeeName = employeeProperties.getName();
String employeeDept = employeeProperties.getDept();
}