java application 存取值_如何访问Spring Boot中application.properties文件中定义的值

问题

我想访问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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值