前言
SpringBoot的配置文件与类之间的属性绑定(@ConfigurationProperties)是通过Setter方法来进行绑定对应的配置值,而从springboot2.2版本开始支持了构造函数的方式进行绑定。添加该注解的属性配置类不再需要添加Setter方法,不过需要添加构造函数,根据构造函数进行实例化属性配置类。
这种注解适用于某些情况下要对某些配置做处理后再设置到类中。
一、添加测试配置信息
在application.properties或application.yml中添加配置:
#token过期时间(分钟)
token.expire=1440m
#是否将token写入cookie
token.cookie-store=true
#token保存在cookie的时间(默认与浏览器生命周期一致)
token.cookie-expire=-1
#token生成方式暂时支持hmac256和rsa两种
token.creator-mode=rsa
注意多个单词间使用-
分割是可以的,但不能使用.
,这与之前使用Setter方式是不一样的。
二、使用步骤
1.编写配置实体类
注意配置类上添加了@ConstructorBinding
注解,不能再使用@Component
,以前使用@Setter注入的一些注解,比如@DefaultValue、@Duration都是支持的,需要写在构造器的属性上。
下面这个配置类TokenProps中createMode做了特殊处理。
package com.iscas.base.biz.config.auth;
import com.iscas.base.biz.util.JWTUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConstructorBinding;
import org.springframework.boot.convert.DurationUnit;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
/**
* token配置表
*
* @author zhuquanwen
* @vesion 1.0
* @date 2018/7/17 8:31
* @since jdk1.8
*/
@Data
//@Component
@ConstructorBinding
@ConfigurationProperties(prefix = "token")
public class TokenProps {
/**token过期时间(分钟)*/
private Duration expire = Duration.ofMinutes(14440);
/** token保存在cookie的时间(毫秒)*/
private int cookieExpire = -1;
/**是否将token存入cookie*/
private boolean cookieStore;
/**
* token生成方式
* */
private JWTUtils.AlgorithmType creatorMode;
public TokenProps(@DurationUnit(ChronoUnit.MINUTES) Duration expire,
Integer cookieExpire, boolean cookieStore, String creatorMode) {
this.expire = expire;
this.cookieExpire = cookieExpire;
this.cookieStore = cookieStore;
this.creatorMode = JWTUtils.AlgorithmType.getEnum(creatorMode);
}
}
public class JWTUtils {
private JWTUtils() {
}
public enum AlgorithmType {
/**
* HMAC256
*/
HMAC256("hmac256"),
/**
* RSA
*/
RSA("rsa");
private String value;
public String getValue() {
return value;
}
AlgorithmType(String value) {
this.value = value;
}
public static AlgorithmType getEnum(String value) {
return Arrays.stream(AlgorithmType.values())
.filter(type -> type.value.equalsIgnoreCase(value))
.findFirst()
.orElse(null);
}
}
}
2.编写配置类
注意使用@EnableConfigurationProperties
package com.iscas.base.biz.config.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
*
* @author zhuquanwen
* @vesion 1.0
* @date 2021/12/28 9:58
* @since jdk1.8
*/
@Configuration
@EnableConfigurationProperties(value = TokenProps.class)
public class TokenConfig {
@Autowired
private TokenProps tokenProps;
}