SpringBoot工具类直接读取配置文件内容
版本
- springboot 2.x
- maven
场景
- 需求 : 工具类直接读取配置文件内容 这样就可以直接:Tools.xxxName方便取值
- 组成 :
A.配置文件 : application.yml B.工具类内容 : JWTUtil.java C.注入容器类 : JWTConfigProperties.java
- 方法 : 配置文件注入工具类作为静态变量
代码
-
application.yml配置文件:
jwt: userPrimaryKey: userId expireTokenKeyPrefix: jwt:token expireTime: 60000 refreshTokenExpire: 604800000
-
工具类
@Slf4j @Component public class JWTUtil { /** * 读取配置文件到常量中 */ public static JWTConfigProperties gogalConfig; public static String userPrimaryKey; public static Long expireTime; public static Long refreshTokenExpire; @Autowired private JWTConfigProperties jwtConfigProperties; /** * 静态方法想使要使用一个非静态对象,需要做一个初始化【重要】 */ @PostConstruct public void init() { gogalConfig = jwtConfigProperties; userPrimaryKey = jwtConfigProperties.getUserPrimaryKey(); expireTime = jwtConfigProperties.getExpireTime(); refreshTokenExpire = jwtConfigProperties.getRefreshTokenExpire(); } }
-
注入容器类
@Component @ConfigurationProperties(prefix = "jwt") @Data public class JWTConfigProperties { private String userPrimaryKey; private String expireTokenKeyPrefix; /** * jwt过期时间,默认2小时,单位为毫秒 */ private Long expireTime = 7200000L; /** * <pre> * refresh_token过期时间,默认7天,单位为毫秒 * * 常用时间: * 1 day:86400000 * 7 day:604800000 * 14 day:1209600000 * 30 day:2592000000 * </pre> */ private Long refreshTokenExpire = 604800000L; }
测试例子
- 注入Web的启动类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = WxApplication.class)
@ActiveProfiles("dev")
@Slf4j
public class xxxTest {
@Test
public void testParams() {
log.info(" v0 {}",JSON.toJSONString(JWTUtil.gogalConfig));
log.info(" v1 {}",JWTUtil.expireTime);
log.info(" v2 {}",JWTUtil.userPrimaryKey);
log.info(" v3 {}",JWTUtil.refreshTokenExpire);
}
}
返回的结果:
v0 {"expireTime":60000,"expireTokenKeyPrefix":"jwt:token","refreshTokenExpire":604800000,"userPrimaryKey":"userId"}
v1 60000
v2 userId
v3 604800000
- 未注入启动类,仅仅是个单元测试
@RunWith(SpringRunner.class)
@Slf4j
public class SimpleTest {
/**
* 没有在web容器导致下面是为 :null
*/
@Test
public void testParams() {
log.info(" v0 {}",JSON.toJSONString(JWTUtil.gogalConfig));
log.info(" v1 {}",JWTUtil.expireTime);
log.info(" v2 {}",JWTUtil.userPrimaryKey);
log.info(" v3 {}",JWTUtil.refreshTokenExpire);
}
}
返回的结果:
16:08:25.998 [main] INFO Simple.SimpleTest - v0 null
16:08:26.004 [main] INFO Simple.SimpleTest - v1 null
16:08:26.004 [main] INFO Simple.SimpleTest - v2 null
16:08:26.004 [main] INFO Simple.SimpleTest - v3 null
- 以上的测试是不一样的,需要在web容器下,初始化赋值才会读取配置文件