我想访问应用程序中提供的值。属性,例如:

logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log

userBucket.path=${HOME}/bucket

我想访问userBucket。在Spring Boot应用程序的主程序中的路径。


当前回答

@ value (" $ {userBucket.path} ") private String userBucketPath;

其他回答

可以使用@Value注释从应用程序中读取值。属性/ yml文件。

@Value("${application.name}")
private String applicationName;

@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;

有两种方法,

你可以直接在类中使用@Value

    @Value("#{'${application yml field name}'}")
    public String ymlField;

OR

要使它干净,你可以清除@Configuration类,在那里你可以添加所有的@value

@Configuration
public class AppConfig {

    @Value("#{'${application yml field name}'}")
    public String ymlField;
}

为了从属性文件中选择值,我们可以有一个配置读取器类,比如ApplicationConfigReader.java 然后根据属性定义所有变量。参考下面的例子,

application.properties

myapp.nationality: INDIAN
myapp.gender: Male

下面是相应的阅读类。

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "myapp") 
class AppConfigReader{
    private String nationality;
    private String gender

    //getter & setter
}

现在,我们可以在任何想要访问属性值的地方自动连接阅读器类。 如。

@Service
class ServiceImpl{
    @Autowired
    private AppConfigReader appConfigReader;

    //...
    //fetching values from config reader
    String nationality = appConfigReader.getNationality() ; 
    String gender = appConfigReader.getGender(); 
}

@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();

}