我正在寻找一种方法来操作初始化时定义的@ConfigurationProperties
,这样当@Inject / @Autorwired
使用@Bean
方法配置的对象时,它就会被正确配置。
情景:
我在.yml
文件中设置了一堆属性。因为所有这些属性都与字符串匹配,所以它们中的一些需要特殊处理才能正确配置为各自的类型(其中一些是枚举)。我是否将我的属性对象设为@Component
,然后将其注入@Bean
方法并进行修改?我尝试组合@Bean
和@ConfigurationProperties
注释,但是在@Bean
方法本身返回之后配置对象,因此任何操作都将丢失/不可能。这样做的最佳方式是什么?
实施例:
在我的.yml
我有这个:
properties:
sports:
"football": ["Team 1", "Team 2", "Team 3"]
"basketball": ["Team 4", "Team 5", "Team 6"]
settings:
"football":
"period1": "45"
"period2": "90"
"players": "11"
"basketball":
"periods": "4"
"players": "5"
这些与以下对象匹配:
Map<SportsEnum, List<TeamsEnum>
Map<SportsEnum, Map<SportSettingsEnum, String>>
TL; DR:
我想从.yml/.properties
文件中获取一个对象并操纵其可注入表示。请提供具体的例子!
答案 0 :(得分:3)
这肯定是支持的,我的猜测是你做错了什么。让我们一步一步走。
首先,您的YAML文件格式错误,它应该如下所示:
properties:
sports:
football:
- Team1
- Team2
- Team3
basketball:
- Team4
- Team5
- Team6
settings:
football:
period1: 45
period2: 90
players: 11
basketball:
periods: 4
players: 5
然后,您的配置属性如下所示:
@ConfigurationProperties(prefix = "properties", locations = "classpath:sports.yml")
public class SportsProperties {
private Map<SportsEnum, List<TeamsEnum>> sports;
private Map<SportsEnum, Map<SportSettingsEnum, String>> settings;
public Map<SportsEnum, List<TeamsEnum>> getSports() {
return sports;
}
public void setSports(Map<SportsEnum, List<TeamsEnum>> sports) {
this.sports = sports;
}
public Map<SportsEnum, Map<SportSettingsEnum, String>> getSettings() {
return settings;
}
public void setSettings(
Map<SportsEnum, Map<SportSettingsEnum, String>> settings) {
this.settings = settings;
}
@PostConstruct
public void customManipulation() {
System.out.println(sports);
System.out.println(settings);
}
}
接下来,应在配置中启用属性:
@SpringBootApplication
@EnableConfigurationProperties(SportsProperties.class)
public class YamlSampleApplication {
public static void main(String[] args) {
SpringApplication.run(YamlSampleApplication.class, args);
}
}
应该是这样,真的。这是我的枚举:
public enum SportsEnum {
football, basketball
}
public enum TeamsEnum {
Team1, Team2, Team3, Team4, Team5, Team6
}
public enum SportSettingsEnum {
periods, period1, period2, players
}
这是我在日志中得到的输出:
2016-07-26 17:44:41.226 DEBUG 30015 --- [ main] s.b.e.YamlPropertySourceLoader$Processor : Loading from YAML: class path resource [sports.yml]
2016-07-26 17:44:41.282 DEBUG 30015 --- [ main] s.b.e.YamlPropertySourceLoader$Processor : Matched document with default matcher: {properties={sports={football=[Team1, Team2, Team3], basketball=[Team4, Team5, Team6]}, settings={football={period1=45, period2=90, players=11}, basketball={periods=4, players=5}}}}
2016-07-26 17:44:41.282 DEBUG 30015 --- [ main] s.b.e.YamlPropertySourceLoader$Processor : Loaded 1 document from YAML resource: class path resource [sports.yml]
{football=[Team1, Team2, Team3], basketball=[Team4, Team5, Team6]}
{football={period1=45, period2=90, players=11}, basketball={periods=4, players=5}}