我想访问应用程序中提供的值。属性,例如:
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log
userBucket.path=${HOME}/bucket
我想访问userBucket。在Spring Boot应用程序的主程序中的路径。
我想访问应用程序中提供的值。属性,例如:
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log
userBucket.path=${HOME}/bucket
我想访问userBucket。在Spring Boot应用程序的主程序中的路径。
当前回答
我也有这个问题。但是有一个很简单的解决办法。只需要在构造函数中声明你的变量。
我的例子:
application.propperties:
#Session
session.timeout=15
SessionServiceImpl经济舱:
private final int SESSION_TIMEOUT;
private final SessionRepository sessionRepository;
@Autowired
public SessionServiceImpl(@Value("${session.timeout}") int sessionTimeout,
SessionRepository sessionRepository) {
this.SESSION_TIMEOUT = sessionTimeout;
this.sessionRepository = sessionRepository;
}
其他回答
实际上有三种方法来读取应用程序。属性文件,
使用环境,
@Autowired
Environment environment
environment.getProperty({propertyName})
或者使用@Value,
@Value("${property}")
但是@Value的问题是,如果值不在属性文件中,它可能会抛出异常
建议使用@ConfigurationProperties
@ConfigurationProperties("userBucket")
public class test{
private String path;
//getters and setters
}
详细示例-读取application.properties
您可以使用@Value从应用程序加载变量。如果你在一个地方使用这个值,那么@ConfigurationProperties是一个更好的方法,但是如果你需要一个更集中的方式来加载这些变量。
此外,如果需要不同的数据类型来执行验证和业务逻辑,则可以加载变量并自动转换它们。
application.properties
custom-app.enable-mocks = false
@Value("${custom-app.enable-mocks}")
private boolean enableMocks;
@ConfigurationProperties可以用来将值从.properties(.yml也支持)映射到POJO。
考虑下面的示例文件。
. 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
}
现在可以通过如下方式自动装配employeeProperties来访问属性值。
@Autowired
private Employee employeeProperties;
public void method() {
String employeeName = employeeProperties.getName();
String employeeDept = employeeProperties.getDept();
}
应用程序。Yml或application.properties
config.value1: 10
config.value2: 20
config.str: This is a simle str
MyConfig类
@Configuration
@ConfigurationProperties(prefix = "config")
public class MyConfig {
int value1;
int value2;
String str;
public int getValue1() {
return value1;
}
// Add the rest of getters here...
// Values are already mapped in this class. You can access them via getters.
}
任何想要访问配置值的类
@Import(MyConfig.class)
class MyClass {
private MyConfig myConfig;
@Autowired
public MyClass(MyConfig myConfig) {
this.myConfig = myConfig;
System.out.println( myConfig.getValue1() );
}
}
最简单的方法是使用Spring Boot提供的@Value注释。您需要在类级别定义一个变量。例如:
@ value (" $ {userBucket.path} ") private字符串userBucketPath
还有另一种方法可以通过环境类来做到这一点。例如:
自动装配环境变量到你的类,你需要访问这个属性:
@ autowired 私人环境环境
使用环境变量在你需要的行中获取属性值:
environment.getProperty(“userBucket.path”);
希望这能回答你的问题!