- 如果有工具类的静态变量需要读取配置文件(主要指 springboot 的配置文件),而又不想让工具类作为一个
bean
存在 - 可以使用代理模式注入
一些属性
jwt:
secretKey: )nikonikoni520akarin20200115)
# 业务 token
accessTokenExpireTime: PT2H
# pc 端刷新 token
refreshTokenExpireTime: PT8H
# app 端刷新 token
refreshTokenExpireAppTime: P30D
issuer: nekosighed.com
一个工具类
/**
* jwt 工具类
*/
@Slf4j
public class JwtUtil {
// 下面是需要读取配置文件中的
private static String secretKey;
private static Duration accessTokenExpireTime;
private static Duration refreshTokenExpireTime;
private static Duration refreshTokenExpireAppTime;
private static String issuer;
/**
* 让代理类 SetStaticValue2Util 来调用
*
* @param jwtReadValue 真正读取配置文件的类
*/
public static void setStaticValue(JwtReadValue jwtReadValue) {
secretKey = jwtReadValue.getSecretKey();
accessTokenExpireTime = jwtReadValue.getAccessTokenExpireTime();
refreshTokenExpireTime = jwtReadValue.getRefreshTokenExpireTime();
refreshTokenExpireAppTime = jwtReadValue.getRefreshTokenExpireAppTime();
issuer = jwtReadValue.getIssuer();
base64SignKey = DatatypeConverter.parseBase64Binary(secretKey);
}
// 其他方法
}
一个真正读取配置文件的类
@Component
@ConfigurationProperties(prefix = "jwt")
@Data
public class JwtReadValue {
private String secretKey;
private Duration accessTokenExpireTime;
private Duration refreshTokenExpireTime;
private Duration refreshTokenExpireAppTime;
private String issuer;
}
代理注入类
/**
* 给工具类们设置静态变量
*/
@Component
public class SetStaticValue2Util {
/**
* 调用工具类们的方法
*
* @param jwtReadValue
*/
public SetStaticValue2Util(JwtReadValue jwtReadValue) {
JwtUtil.setStaticValue(jwtReadValue);
}
}