springboot项目我们一般都是将配置信息维护到application.yml中,在代码中很多时候是通过@Value的方式去读取某些配置,如读取当前应用端口
@Value("${server.port:8084}")
private String serverPort;
假设现在有个需求是需要做个系统的监控功能,我们需要有默认的监控参数,并且针对不同的子系统还可以定制化修改配置参数,在匹配到子系统时就是用子系统的参数,没匹配到就使用默认参数
此时我们通过@Value的方式去读取配置就无法满足业务需求,这时我们可以使用@ConfigurationProperties并结合配置类的方式改造读取配置,假设yml中参数如下:
monitor-param:
core-size: 5
max-size: 10
features:
wms-101:
core-size: 20
max-size: 25
hrs-201:
core-size: 50
max-size: 42
设计配置类
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Data
@Configuration
@ConfigurationProperties(prefix = "monitor-param")
public class MonitorParamConfig {
/**
* 核心数量
*/
private int coreSize = 1;
/**
* 最大数量
*/
private int maxSize = 3;
/**
* 特殊配置映射
*/
private Map<String, FeatureParamConfig> features = new HashMap<>();
public int getCoreSize(String featureName) {
if (features.containsKey(featureName) && features.get(featureName) != null && StringUtils.isNotBlank(features.get(featureName).getCoreSize())) {
return Integer.parseInt(features.get(featureName).getCoreSize());
}
return coreSize;
}
public int getMaxSize(String featureName) {
if (features.containsKey(featureName) && features.get(featureName) != null && StringUtils.isNotBlank(features.get(featureName).getMaxSize())) {
return Integer.parseInt(features.get(featureName).getMaxSize());
}
return maxSize;
}
@Data
private static class FeatureParamConfig {
/**
* 核心数量
*/
private String coreSize;
/**
* 最大数量
*/
private String maxSize;
}
}
简单测试下效果
import com.yx.light.element.jpa.config.MonitorParamConfig;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@Slf4j
class LightElementJpaApplicationTests {
@Autowired
private MonitorParamConfig monitorParamConfig;
@Test
void testConfigLoad() {
int coreSize = monitorParamConfig.getCoreSize();
log.info("默认核心数量:{}", coreSize);
int maxSize = monitorParamConfig.getMaxSize();
log.info("默认最大数量:{}", maxSize);
int coreSizeWMS = monitorParamConfig.getCoreSize("wms-101");
log.info("WMS核心数量:{}", coreSizeWMS);
int maxSizeWMS = monitorParamConfig.getMaxSize("wms-101");
log.info("WMS最大数量:{}", maxSizeWMS);
int coreSizeHRS = monitorParamConfig.getCoreSize("hrs-201");
log.info("HRS核心数量:{}", coreSizeHRS);
int maxSizeHRS = monitorParamConfig.getMaxSize("hrs-201");
log.info("HRS最大数量:{}", maxSizeHRS);
}
}

2万+

被折叠的 条评论
为什么被折叠?



