我想访问应用程序中提供的值。属性,例如:
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应用程序的主程序中的路径。
当前回答
有3种方法读取application.properties,
使用@Value, EnvironmentInterface和@ConfigurationProperties..
@Value(${userBucket.path})
private String value;
方式2:
@Autowired
private Environment environment;
String s = environment.getProperty("userBucket.path");
第三道:
@ConfigurationProperties("userbucket")
public class config {
private String path;
//getters setters
}
可以读取与getter和setter ..
参考资料-此处
其他回答
您可以使用@Value从应用程序加载变量。如果你在一个地方使用这个值,那么@ConfigurationProperties是一个更好的方法,但是如果你需要一个更集中的方式来加载这些变量。
此外,如果需要不同的数据类型来执行验证和业务逻辑,则可以加载变量并自动转换它们。
application.properties
custom-app.enable-mocks = false
@Value("${custom-app.enable-mocks}")
private boolean enableMocks;
遵循以下步骤。 1:-创建你的配置类如下所示
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
@Bean
public String getUserBucketPath() {
return userBucket;
}
}
2:-当你有一个配置类时,然后从你需要的配置中注入变量。
@Component
public class YourService {
@Autowired
private String getUserBucketPath;
// now you have a value in getUserBucketPath varibale automatically.
}
最简单的方法是使用Spring Boot提供的@Value注释。您需要在类级别定义一个变量。例如:
@ value (" $ {userBucket.path} ") private字符串userBucketPath
还有另一种方法可以通过环境类来做到这一点。例如:
自动装配环境变量到你的类,你需要访问这个属性:
@ autowired 私人环境环境
使用环境变量在你需要的行中获取属性值:
environment.getProperty(“userBucket.path”);
希望这能回答你的问题!
获取财产价值的最佳方法是使用。
1. 使用Value注释
@Value("${property.key}")
private String propertyKeyVariable;
2. 使用环境bean
@Autowired
private Environment env;
public String getValue() {
return env.getProperty("property.key");
}
public void display(){
System.out.println("# Value : "+getValue);
}
从应用程序中获取价值有两种方法。属性文件
使用@Value注释
@Value("${property-name}")
private data_type var_name;
使用环境类的实例
@Autowired
private Environment environment;
//access this way in the method where it's required
data_type var_name = environment.getProperty("property-name");
您还可以使用构造函数注入或自己创建bean来注入环境实例