我想访问应用程序中提供的值。属性,例如:
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应用程序的主程序中的路径。
当前回答
获取财产价值的最佳方法是使用。
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);
}
其他回答
也许它可以帮助其他人: 你应该注入@Autowired私有环境env;from import org.springframework.core. environment;
然后这样使用它: env.getProperty(“yourPropertyNameInApplication.properties”)
@Value Spring注释用于向Spring管理的bean中的字段注入值,它可以应用于字段或构造函数/方法参数级别。
例子
从注释到字段的字符串值
@Value("string value identifire in property file")
private String stringValue;
我们还可以使用@Value注释来注入Map属性。 首先,我们需要在属性文件中的{key: ' value'}形式中定义属性:
valuesMap={key1: '1', key2: '2', key3: '3'}
并不是说Map中的值必须是单引号。
现在从属性文件中注入这个值作为Map:
@Value("#{${valuesMap}}")
private Map<String, Integer> valuesMap;
来获取特定键的值
@Value("#{${valuesMap}.key1}")
private Integer valuesMapKey1;
我们还可以使用@Value注释来注入List属性。
@Value("#{'${listOfValues}'.split(',')}")
private List<String> valuesList;
对我来说,以上这些方法对我都没有直接作用。 我所做的是:
另外,我补充了@Rodrigo Villalba Zayas的回答 实现InitializingBean到类 并实现了该方法
@Override
public void afterPropertiesSet() {
String path = env.getProperty("userBucket.path");
}
这看起来就像
import org.springframework.core.env.Environment;
public class xyz implements InitializingBean {
@Autowired
private Environment env;
private String path;
....
@Override
public void afterPropertiesSet() {
path = env.getProperty("userBucket.path");
}
public void method() {
System.out.println("Path: " + path);
}
}
应用程序可以从应用程序中读取3种类型的值。属性文件。
application.properties
my.name=kelly
my.dbConnection ={connection_srting:'http://localhost:...',username:'benz',password:'pwd'}
类文件
@Value("${my.name}")
private String name;
@Value("#{${my.dbConnection}}")
private Map<String,String> dbValues;
如果你在申请中没有房产。属性,则可以使用默认值
@Value("${your_name : default value}")
private String msg;
有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 ..
参考资料-此处