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

本文详细介绍JWT在Spring Boot项目中的配置方式,包括application.yml文件的设置,TokenSettings类的定义,以及静态工具类和代理类的实现过程,为开发者提供了一个完整的JWT集成解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值