• 如果有工具类的静态变量需要读取配置文件(主要指 springboot 的配置文件),而又不想让工具类作为一个 bean 存在
  • 可以使用代理模式注入

一些属性

  1. jwt:
  2. secretKey: )nikonikoni520akarin20200115)
  3. # 业务 token
  4. accessTokenExpireTime: PT2H
  5. # pc 端刷新 token
  6. refreshTokenExpireTime: PT8H
  7. # app 端刷新 token
  8. refreshTokenExpireAppTime: P30D
  9. issuer: nekosighed.com

一个工具类

  1. /**
  2. * jwt 工具类
  3. */
  4. @Slf4j
  5. public class JwtUtil {
  6. // 下面是需要读取配置文件中的
  7. private static String secretKey;
  8. private static Duration accessTokenExpireTime;
  9. private static Duration refreshTokenExpireTime;
  10. private static Duration refreshTokenExpireAppTime;
  11. private static String issuer;
  12. /**
  13. * 让代理类 SetStaticValue2Util 来调用
  14. *
  15. * @param jwtReadValue 真正读取配置文件的类
  16. */
  17. public static void setStaticValue(JwtReadValue jwtReadValue) {
  18. secretKey = jwtReadValue.getSecretKey();
  19. accessTokenExpireTime = jwtReadValue.getAccessTokenExpireTime();
  20. refreshTokenExpireTime = jwtReadValue.getRefreshTokenExpireTime();
  21. refreshTokenExpireAppTime = jwtReadValue.getRefreshTokenExpireAppTime();
  22. issuer = jwtReadValue.getIssuer();
  23. base64SignKey = DatatypeConverter.parseBase64Binary(secretKey);
  24. }
  25. // 其他方法
  26. }

一个真正读取配置文件的类

  1. @Component
  2. @ConfigurationProperties(prefix = "jwt")
  3. @Data
  4. public class JwtReadValue {
  5. private String secretKey;
  6. private Duration accessTokenExpireTime;
  7. private Duration refreshTokenExpireTime;
  8. private Duration refreshTokenExpireAppTime;
  9. private String issuer;
  10. }

代理注入类

  1. /**
  2. * 给工具类们设置静态变量
  3. */
  4. @Component
  5. public class SetStaticValue2Util {
  6. /**
  7. * 调用工具类们的方法
  8. *
  9. * @param jwtReadValue
  10. */
  11. public SetStaticValue2Util(JwtReadValue jwtReadValue) {
  12. JwtUtil.setStaticValue(jwtReadValue);
  13. }
  14. }