Spring如何移除配置名前缀且不修改变量与配置属性名?
问题描述
现有配置
a-configuration-group: some-hyphen-val1: xxx some-hyphen-val2: yyy ... some-hyphen-valn: zzz
当前代码使用方式
public class SomeClass { @Value("${a-configuration-group.some-hyphen-val1}") private String someHyphenVal1; @Value("${a-configuration-group.some-hyphen-val2}") private String someHyphenVal2; }
核心需求
- 消除代码中重复出现的
a-configuration-group.前缀; - 不能修改Java变量名(比如不能改成不符合编码规范的
String some-hyphen-val1); - 不能修改配置文件中的属性名,因为该配置已在多个类和外部配置文件中使用,修改成本太高。
已知Spring的@ConfigurationProperties注解,但它似乎和上述第2或第3点冲突,想问有没有类似的方案,既能保留@Value注解,又能满足所有需求?
解决方案
方法1:用静态常量拼接前缀(最推荐)
直接在类里定义一个static final的前缀常量,然后在@Value里通过字符串拼接复用这个前缀,完全符合你的要求:
public class SomeClass { // 只需要维护这一处前缀 private static final String CONFIG_PREFIX = "a-configuration-group."; @Value("${" + CONFIG_PREFIX + "some-hyphen-val1}") private String someHyphenVal1; @Value("${" + CONFIG_PREFIX + "some-hyphen-val2}") private String someHyphenVal2; }
这种写法是Spring原生支持的,不需要额外写自定义代码,既不用改配置名,也不用改变量名,还彻底消除了重复前缀。
方法2:结合Environment的灵活写法(适合动态前缀场景)
如果你的前缀需要从其他配置动态读取,或者想更灵活地处理属性,可以借助Spring的Environment来获取配置,同样能复用前缀:
import org.springframework.core.env.Environment; import org.springframework.beans.factory.annotation.Autowired; public class SomeClass { private static final String CONFIG_PREFIX = "a-configuration-group."; private String someHyphenVal1; private String someHyphenVal2; // 构造注入Environment(推荐方式) @Autowired public SomeClass(Environment environment) { this.someHyphenVal1 = environment.getProperty(CONFIG_PREFIX + "some-hyphen-val1"); this.someHyphenVal2 = environment.getProperty(CONFIG_PREFIX + "some-hyphen-val2"); } }
不过这种方式需要手动注入Environment并赋值,比方法1繁琐,适合特殊场景。
关于@ConfigurationProperties的补充说明
你觉得@ConfigurationProperties冲突,可能是误解了它的映射规则:如果你的Java变量名是驼峰式(比如someHyphenVal1),配置属性名是连字符式(some-hyphen-val1),那么@ConfigurationProperties(prefix = "a-configuration-group")是完全可以正常绑定的,而且是Spring官方推荐的批量配置方式:
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "a-configuration-group") public class SomeClass { // 自动绑定a-configuration-group.some-hyphen-val1 private String someHyphenVal1; private String someHyphenVal2; // 需要提供getter/setter,或者用Lombok的@Data简化 public String getSomeHyphenVal1() { return someHyphenVal1; } public void setSomeHyphenVal1(String someHyphenVal1) { this.someHyphenVal1 = someHyphenVal1; } // 其他属性的getter/setter }
只有当你的变量名和配置名完全不遵循驼峰-连字符的映射规则时,才会出现冲突,这时候方法1就是最直接的替代方案。
内容的提问来源于stack exchange,提问作者grunt
相关产品推荐
相关产品推荐

