@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "app.prefix")
public class SomeProperties {
private Map<String, SomeEnum> someEnumMappings;
}
在我的 application.yml 中:
app:
prefix:
someEnumMappings:
"Name-1": SOME_ENUM_1
"Anthr. Name": SOME_ENUM_2
但我得到:
Failed to bind properties under 'app.prefix' to java.util.Map<java.lang.String, com.example.enums.SomeEnum>:
Reason: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.util.Map<java.lang.String, com.example.enums.SomeEnum>]
我可以做什么来预防它?编辑:更改为建议的代码,仍然不起作用。有人可以指出参考文献的链接吗?医生为此?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
其次你的 application.yml 应该在下面
app:
prefix:
someEnumMappings:
Name: SOME_ENUM_1
"Another_Name": SOME_ENUM_2
您应该在 Another Name 属性中使用下划线。你应该在主类中添加
@EnableConfigurationProperties(SomeProperties.class)
。不要忘记这些。!
应用程序.yml
spring:
application:
name: config-prop
app:
prefix:
someEnumMappings:
Name: SOME_ENUM_1
"Another_Name": SOME_ENUM_2
枚举
public enum SomeEnum {
SOME_ENUM_1,
SOME_ENUM_2
}
逻辑类
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "app.prefix")
@Component
public class SomeProperties {
private Map<String, SomeEnum> someEnumMappings;
@Bean
public String output() {
someEnumMappings.forEach((key, value) ->
System.out.println("Key: [" + key + "], Value: [" + value + "]"));
SomeEnum name1 = someEnumMappings.get("Name");
SomeEnum name2 = someEnumMappings.get("Another_Name");
System.out.println("Name: " + name1);
System.out.println("Another_Name: " + name2);
return "";
}
}
主课。
@SpringBootApplication
@EnableConfigurationProperties(SomeProperties.class)
public class ConfigPropApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigPropApplication.class, args);
}
}
输出如下,
Key: [Name], Value: [SOME_ENUM_1]
Key: [Another_Name], Value: [SOME_ENUM_2]
Name: SOME_ENUM_1
Another_Name: SOME_ENUM_2