springboot静态工具类读取配置文件

1、application.yml文件

#jwt秘钥
jwt:
  secretKey: zzzzzzzzzz
  issuer: yingxue.com

2、TokenSettings类

package com.scitech.entity;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component  //将该类对象注入spring容器
@ConfigurationProperties(prefix = "jwt")    //@ConfigurationProperties的作用是从配置文件中获取配置项
//此处建议使用lombok
public class TokenSettings {
    private String secretKey;
    private String issuer;

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getIssuer() {
        return issuer;
    }

    public void setIssuer(String issuer) {
        this.issuer = issuer;
    }

    @Override
    public String toString() {
        return "TokenSettings{" +
                "secretKey='" + secretKey + '\'' +
                ", issuer='" + issuer + '\'' +
                '}';
    }
}

3、静态工具类

/**
 * 静态工具类
 */
public class JwtTokenUtil {

    private static String secretKey;

    private static String issuer;

    public static void setToken(TokenSettings tokenSettings){
        secretKey = tokenSettings.getSecretKey();
        issuer = tokenSettings.getIssuer();
    }

    public static String getToken(){
        return secretKey + issuer;
    }
}

4、代理类

package com.scitech.utils;

import com.scitech.entity.TokenSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 代理类
 */
@Component
public class StaticInitializerUtil {

    @Autowired
    private TokenSettings tokenSettings;

    public StaticInitializerUtil(TokenSettings tokenSettings){
        JwtTokenUtil.setToken(tokenSettings);
    }
}

你可能感兴趣的:(springboot静态工具类读取配置文件)