我想访问应用程序中提供的值。属性,例如:
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应用程序的主程序中的路径。
当前回答
另一种方法是将org.springframework.core. environment注入到bean中。
@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.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;
最好的方法是使用@Value注释,它会自动为你的对象私有环境赋值。 这将减少你的代码,它将很容易过滤你的文件。
可以使用@Value注释从应用程序中读取值。属性/ yml文件。
@Value("${application.name}")
private String applicationName;
1.Injecting a property with the @Value annotation is straightforward:
@Value( "${jdbc.url}" )
private String jdbcUrl;
2. we can obtain the value of a property using the Environment API
@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));
@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;