Spring @Value

@Value can be used for injecting values into fields in Spring-managed beans, and it can be applied at the field or constructor/method parameter level.

Setting Up the Application

We can use placeholder strings in @Value to wire values defined in external sources, for example, in .properties or .yaml files.

# .properties file
value.from.file=Value got from the file
priority=high
listOfValues=A,B,C

设置死值

@Value("string value")
private String stringValue;

读配置文件的值

@Value("${value.from.file}")
private String valueFromFile;

读系统变量的值

@Value("${systemValue}")
private String systemValue;

# 系统变量和配置文件变量重名时,系统变量值优先
@Value("${priority}")
private String prioritySystemProperty;

批量设置值

@Value("${listOfValues}")
private String[] valuesArray;

可以设置默认值

# String Defaults
@Value("${some.key:my-default-value}")
private String stringWithDefaultValue;

# zero-length String as the default value
@Value("${some.key:})"
private String stringWithBlankDefaultValue;

# Primitives
@Value("${some.key:true}")
private boolean booleanWithDefaultValue;

@Value("${some.key:42}")
private int intWithDefaultValue;

# Arrays
@Value("${some.key:one,two,three}")
private String[] stringArrayWithDefaults;

@Value("${some.key:1,2,3}")
private int[] intArrayWithDefaults;

#  Using SpEL
@Value("#{systemProperties['some.key'] ?: 'my default system property value'}")
private String spelWithDefaultValue;

Using @Value With Constructor Injection

@Component
@PropertySource("classpath:values.properties")
public class PriorityProvider {

    private String priority;

    @Autowired
    public PriorityProvider(@Value("${priority:normal}") String priority) {
        this.priority = priority;
    }

    // standard getter
}

Using @Value With Setter Injection

@Component
@PropertySource("classpath:values.properties")
public class CollectionProvider {

    private List<String> values = new ArrayList<>();
    private int cylinderCount;

    @Autowired
    public void setValues(@Value("#{'${listOfValues}'.split(',')}") List<String> values) {
        this.values.addAll(values);
    }

    @Autowired
    void setCylinderCount(@Value("8") int cylinderCount) {
        this.cylinderCount = cylinderCount;
    }

    @Value("8")
    void setCylinderCount(int cylinderCount) {
        this.cylinderCount = cylinderCount;
    }
    // standard getter
}

Using @Value With SpEL expressions

Spring Expression Language (SpEL)

#  If we have a system property named priority, then its value will be applied to the field
#  If we have not defined the system property, then the null value will be assigned.
@Value("#{systemProperties['priority']}")
private String spelValue;

# We get some default value for the field if the system property is not defined
@Value("#{systemProperties['unknown'] ?: 'some default'}")
private String spelSomeDefault;

# We can manipulate properties to get a List of values
@Value("#{'${listOfValues}'.split(',')}")
private List<String> valuesList;

Using @Value With Maps

# First, we'll need to define the property in the {key: ‘value' } form in our properties file.
# Note that the values in the Map must be in single quotes.
valuesMap={key1: '1', key2: '2', key3: '3'}

@Value("#{${valuesMap}}")
private Map<String, Integer> valuesMap;

# get the value of a specific key in the Map
@Value("#{${valuesMap}.key1}")
private Integer valuesMapKey1;

# If we're not sure whether the Map contains a certain key, 
# we should choose a safer expression that will not throw an exception but set the value to null when the key is not found:
@Value("#{${valuesMap}['unknownKey']}")
private Integer unknownMapKey;

# We can also set default values for the properties or keys that might not exist:
@Value("#{${unknownMap : {key1: '1', key2: '2'}}}")
private Map<String, Integer> unknownMap;
@Value("#{${valuesMap}['unknownKey'] ?: 5}")
private Integer unknownMapKeyWithDefaultValue;

# 定制条件
@Value("#{${valuesMap}.?[value>'1']}")
private Map<String, Integer> valuesMapFiltered;

# inject all current system properties
@Value("#{systemProperties}")
private Map<String, String> systemPropertiesMap;

参考:
A Quick Guide to Spring @Value
Using Spring @Value With Defaults

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值