Spring @Value 用法

1. 概述

在 Spring 组件中使用 @Value 注解的方式,很方便的读取 properties 文件的配置值。

2.使用场景

声明的变量中使用。

public static class FieldValueTestBean {

    @Value("#{ systemProperties['user.region'] }")
    private String defaultLocale;

}

setter 方法中。

public static class PropertyValueTestBean {

    private String defaultLocale;

    @Value("#{ systemProperties['user.region'] }")
    public void setDefaultLocale(String defaultLocale) {
        this.defaultLocale = defaultLocale;
    }

}

方法。

public class SimpleMovieLister {

    private MovieFinder movieFinder;
    private String defaultLocale;

    @Autowired
    public void configure(MovieFinder movieFinder,
            @Value("#{ systemProperties['user.region'] }") String defaultLocale) {
        this.movieFinder = movieFinder;
        this.defaultLocale = defaultLocale;
    }

    // ...
}

构造方法。

public class MovieRecommender {

    private String defaultLocale;

    private CustomerPreferenceDao customerPreferenceDao;

    @Autowired
    public MovieRecommender(CustomerPreferenceDao customerPreferenceDao,
            @Value("#{systemProperties['user.country']}") String defaultLocale) {
        this.customerPreferenceDao = customerPreferenceDao;
        this.defaultLocale = defaultLocale;
    }

    // ...
}

 

3. 字符串

字符串类型的属性设置默认值。

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

some.key 没有设置值,stringWithDefaultValue 变量值将会被设置成 my default value 。

如果默认值设为空,也将会被设置成默认值。

@Value("${some.key:}")
private String stringWithBlankDefaultValue;

4. 基本类型

基本类型设置默认值。

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

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

包装类型设置默认值。

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

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

5. 数组

数组的默认值可以使用逗号分割。

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

6. SpEL

使用 Spring Expression Language (SpEL) 设置默认值。

下面的代码标示在systemProperties属性文件中,如果没有设置 some.key 的值,my default system property value 会被设置成默认值。

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

7.结语

上面讲解使用 Spring @Value 为属性设置默认值。在项目中,提供合理的默认值,在大多情况下不用任何配置,就能直接使用。达到零配置的效果,降低被人使用的门槛。简化新Spring应用的搭建、开发、部署过程。

8.参考链接

Using Spring @Value with Defaults

Annotation-based configuration

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值