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

  • Post author:
  • Post category:其他




@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;
    



版权声明:本文为m0_46725089原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。