介绍一下Spring的@Value

官方文档已经介绍了@Value可以用在哪些地方:

  1. 在字段上

    @Value("#{ systemProperties['user.region'] }")
    private String defaultLocale;
    
  2. 在setter方法上(与上面那种设置方式结果相同)

    @Value("#{ systemProperties['user.region'] }")
    public void setDefaultLocale(String defaultLocale) {
        this.defaultLocale = defaultLocale;
    }
    
  3. 在方法参数上

    @Autowired
    public void configure(MovieFinder movieFinder,
    @Value("#{ systemProperties['user.region'] }") String defaultLocale) {
     this.movieFinder = movieFinder;
     this.defaultLocale = defaultLocale;
    }
    
  4. 在构造函数参数上

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

用法

  1. 常规用法

    @Value("${name}")
    private String name;
    
  2. 带有默认值。若在配置文件中没有设置值时,则指定这个为默认值

    @Value("${name:test}")
    private String name;
    
  3. 指定为基础类型

    @Value("${age:10}")
    private int age;
    
    @Value("${isValid:true}")
    private boolean isValid;
    
  4. 指定为数组

    @Value("${keys:name,age,sex}")
    private String[] keys;
    
  5. SpEL

    @Value("#{systemProperties['priority']}")
    private String spelValue;
    
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容