zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

如何获取yml里的配置数据?

2023-04-18 13:17:20 时间

当我们在yml进行一些配置的时候,在Java中需要拿到yml中自定义的配置,我们可以使用 @ConfigurationProperties 注解去读取yml中的配置数据。

使用方式demo

  • 在pom中引入依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
  • 在yml自定义jwt配置

(jwt需要顶格,否则相当于在其他配置下,在Java代码中会拿不到数据)

jwt:
  # 密匙KEY
  secret: JWTSecret
  # HeaderKEY
  tokenHeader: Authorization
  # Token前缀字符
  tokenPrefix: Sans-
  # 过期时间 单位秒 1天后过期=86400 7天后过期=604800
  expiration: 86400
  # 配置不需要认证的接口
  antMatchers: /index/**,/login/**,/favicon.ico

在配置类中获取prefix

@Getter
@Component
@ConfigurationProperties(prefix = "jwt")
public class JWTConfig{
    /**
     * 密钥KEY
     */
    public static String secret;
    /**
     * TokenKey
     */
    public static String tokenHeader;
    /**
     * Token前缀字符
     */
    public static String tokenPrefix;
    /**
     * 过期时间
     */
    public static Integer expiration;
    /**
     * 不需要认证的接口
     */
    public static String antMatchers;


    public void setSecret(String secret) {
        this.secret = secret;
    }

    public void setTokenHeader(String tokenHeader) {
        this.tokenHeader = tokenHeader;
    }

    public void setTokenPrefix(String tokenPrefix) {
        this.tokenPrefix = tokenPrefix;
    }

    public void setExpiration(Integer expiration) {
        this.expiration = expiration * 1000;
    }

    public void setAntMatchers(String antMatchers) {
        this.antMatchers = antMatchers;
    }
}

注意:

  • prefix里的名称要和yml配置名称一致
  • yml定义的属性一定不要使用下划线,要使用驼峰命名,否则会导致获取到的yml属性为Null

重启项目 使用

    @Autowired
    EncryptConfig encryptConfig;

使用@Autowired方式引入

测试

   @Test
    public void test3() {
        System.out.println(encryptConfig.getSecret());
    }