Springboot 使用@Value方法,# 与 &进行注入的区别,初学者使用 @Value(“${}”) 应用举例

@Value

@Value是单独为一个属性值进行赋值的注解,而@ConfigurationProperties是批量地对一个类的属性进行赋值。,注意@Value中可以使用spEL表达式,而@ConfigurationProperties不可。


1 @Value的值有两类

  1. ${ property : default_value } (用于读取配置文件中的属性

该表表达式可以没有冒号“:”,如果没有冒号,那么如果配置文件 application.yml 文件中不存在该变量,那么注入的值为null,如果有分号,当文件中不存在注入标量时,将会按照 default_value 以注入。

  1. #{ obj.property? :default_value } (用于读取bean中的属性或者系统属性(也就是说不能读取yml或者properties中的属性)

#{}里面那个obj代表对象(例如容器中的bean,通过 bean.id 打点调用对象中的属性进行注入 )


2 以@Value(“${}”),举例实现自定义读取配置文件中的值

  1. 在配值文件中定义好对应的值(注意 yml 的语法,“:”冒号后需要一个空格,然后才是属性值),例如:

    ca:
      cert-path: cert.txt
      key-path: key.tx
    
  2. 根据idea的提示信息,对自定义值进行下定义

idea提示

将会自动创建文件 additional-spring-configuration-metadata.json,并填充信息如下:

{
  "properties": [
    {
      "name": "ca.cert-path",
      "type": "java.lang.String",
      "description": "Description for ca.cert-path."
    },
    {
      "name": "ca.key-path",
      "type": "java.lang.String",
      "description": "Description for ca.key-path."
    }
  ] }
  1. 将需要注入配置属性的类注入到Spring容器中(也就是使用@Component或者@Service等注解)

    @Component
    public class CertAndKeyUtility {
        @Value("${ca.cert-path}")
        private  String certPath;
    
        @Value("${ca.key-path}")
        private  String keyPath;
        public  Pair<String, String> getCertAndPrivateKey(String cn) throws Exception {
            String key= FileUtil.getContentWithClasspath(keyPath);
            String cert= FileUtil.getContentWithClasspath(certPath);
            return X509Utility.signFor(cert,key,cn);
        }
     
    }
    

    注意@value中的spEL表达式需要打点调用属性

  2. 之后当我们需要使用这个类的相关方法时(例如使用测试方法测试),只需要注入该类的bean,即其正常在其方法中使用@Value注入的配置属性。

    @Autowired
    CertAndKeyUtility certAndKeyUtility;
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值