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

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

userBucket.path=${HOME}/bucket

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


当前回答

@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注释并访问您所使用的Spring bean中的属性

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

Spring Boot文档的Externalized Configuration部分解释了您可能需要的所有细节。

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;

你也可以这样做....

@Component
@PropertySource("classpath:application.properties")
public class ConfigProperties {

    @Autowired
    private Environment env;

    public String getConfigValue(String configKey){
        return env.getProperty(configKey);
    }
}

然后无论你想从应用程序中读取什么。属性,只需将键传递给getConfigValue方法。

@Autowired
ConfigProperties configProp;

// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port"); 

属性中的@Value("${property-name}") 应用程序。属性 @配置或@组件。

我尝试的另一种方法是用下面的方式创建一个Utility类来读取属性

 protected PropertiesUtility () throws IOException {
    properties = new Properties();
    InputStream inputStream = 
   getClass().getClassLoader().getResourceAsStream("application.properties");
    properties.load(inputStream);
}

您可以使用静态方法来获取作为参数传递的键的值。