SpringBoot将配置文件中的属性值绑定到实体类中

在日常开发中有一些常量我们可以在配置文件中设置值,然后我们在Java代码中也需要用到。这时我们可以将配置文件中的值绑定到实体类的属性中,然后在代码中调用实体类中的静态变量就行。

接下来用一个例子来说明如何操作,就比如我们使用阿里云的OSS对象存储服务时,在Java代码中需要设置endpoint,accessKeyId,accessKeySecret,bucketName 这四个属性值。

先在配置文件中设置一下值

aliyun.oss.file.endpoint=yourendpoint
aliyun.oss.file.keyid=yourkeyid
aliyun.oss.file.keysecret=yourkeysecret
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=yourbucketname

然后创建一个java类来绑定配置文件中的属性值 这个类需要实现InitializingBean接口,这个接口是spring提供的(当项目启动时,这个接口可以帮助我们初始化bean)具体看下面代码

package com.atguigu.oss.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 该工具类可以读取配置文件中的常量
 * </P>
 *
 * @author Kk
 * @since 2022/2/25 20:07
 */
//当项目一启动,spring有一个接口InitializingBean,可以初始化bean
@Component
public class ConstantPropertiesUtils implements InitializingBean {
          
   

    //读取配置文件中的内容
    @Value("${aliyun.oss.file.endpoint}") //属性注解,能将括号中的值注入到属性中去
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    public static String END_POINT;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;

    @Override
    public void afterPropertiesSet() throws Exception {
          
   
        END_POINT = endpoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
    }
}

其中使用@Value 注解来将配置文件中的值绑定到对应的变量上 @Value 注解里面用${}包裹上配置文件中属性全称,如@Value("${aliyun.oss.file.endpoint}") 创建四个静态变量,在实现的InitializingBean接口中的afterPropertiesSet方法中将上面绑定的变量值赋给这四个静态变量,这样就能直接用这个类.出静态变量直接使用了,如

经验分享 程序员 微信小程序 职场和发展