spring注解之@Value详解

前言:为了把程序中用到零零散散的配置信息变得容易维护,我们会把这些信息写进配置文件,那么怎么从配置文件读出这些信息呢?@Value、@ConfigurationProperties帮你解决

@Value注解作用

该注解的作用是将我们配置文件的属性通过前缀匹配的方式读出来,有@Value(“${}”)和@Value(“#{}”)两种方式。

使用

在springBoot项目中,application.yml中配置了如下信息
在这里插入图片描述

/**
 * @author zzh
 * @class
 */
@Component
@Data
public class paramsConfig {
    
    
    @Value("${Good.name}")
    private String goodName;
    @Value("#{1+1}")
    private String jGoodPrice;
    @Value("${Good.price}")
    private String goodPrice;
    @Value("${Good.bad:null}")
    private String goodbad;
}

运行结果

在这里插入图片描述

@Value(“${}”)与@Value(“#{}”)区别

① ${ property : default_value }
② #{ obj.property? :default_value }
第一个注入的是外部配置文件对应的property,第二个则是SpEL表达式对应的内容。default_value是前面的值为空时的默认值。注意二者的不同,#{}里面那个obj代表对象

@ConfigurationProperties注解使用

https://blog.csdn.net/qq_42875345/article/details/113521999

猜你喜欢

转载自blog.csdn.net/qq_42875345/article/details/113269196