当我们在yml进行一些配置的时候,在Java中需要拿到yml中自定义的配置,我们可以使用 @ConfigurationProperties 注解去读取yml中的配置数据。
使用方式demo
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>(jwt需要顶格,否则相当于在其他配置下,在Java代码中会拿不到数据)
jwt:
# 密匙KEY
secret: JWTSecret
# HeaderKEY
tokenHeader: Authorization
# Token前缀字符
tokenPrefix: Sans-
# 过期时间 单位秒 1天后过期=86400 7天后过期=604800
expiration: 86400
# 配置不需要认证的接口
antMatchers: /index/**,/login/**,/favicon.ico在配置类中获取prefix
@Getter
@Component
@ConfigurationProperties(prefix = "jwt")
public class JWTConfig{
/**
* 密钥KEY
*/
public static String secret;
/**
* TokenKey
*/
public static String tokenHeader;
/**
* Token前缀字符
*/
public static String tokenPrefix;
/**
* 过期时间
*/
public static Integer expiration;
/**
* 不需要认证的接口
*/
public static String antMatchers;
public void setSecret(String secret) {
this.secret = secret;
}
public void setTokenHeader(String tokenHeader) {
this.tokenHeader = tokenHeader;
}
public void setTokenPrefix(String tokenPrefix) {
this.tokenPrefix = tokenPrefix;
}
public void setExpiration(Integer expiration) {
this.expiration = expiration * 1000;
}
public void setAntMatchers(String antMatchers) {
this.antMatchers = antMatchers;
}
}注意:
重启项目 使用
@Autowired
EncryptConfig encryptConfig;使用@Autowired方式引入
测试
@Test
public void test3() {
System.out.println(encryptConfig.getSecret());
}