英文:
How do you assign a non string value (enum/class) to application.properties?
问题
我在项目中使用AWS,我只想在属性文件中使Regions
可配置化。
因此,com.amazonaws.regions.Regions
接受枚举值,如Regions.AP_EAST_1
。
我尝试在application.properties
中进行赋值:
aws.s3.config.region=com.amazonaws.regions.Regions.US_WEST_2
@Value("${aws.s3.config.region}")
private Regions clientRegion;
但这并不起作用。它给我返回了以下错误信息:
> java.lang.IllegalStateException: 无法将类型为[java.lang.String]的值转换为所需类型[com.amazonaws.regions.Regions]:找不到匹配的编辑器或转换策略
英文:
I'm using AWS in my project and I just want to make Regions
configurable in properties file.
So com.amazonaws.regions.Regions
accepts enum values like Regions.AP_EAST_1
.
I tried assigning it in application.properties
:
aws.s3.config.region=com.amazonaws.regions.Regions.US_WEST_2
@Value("${aws.s3.config.region}")
private Regions clientRegion;
This just doesn't work out. It gives me this:
> java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.amazonaws.regions.Regions]: no matching editors or conversion strategy found
答案1
得分: 2
Spring知道如何映射枚举。只需使用枚举值(而不是完全限定的名称):
aws.s3.config.region: US_WEST_2
还要注意,Spring Cloud AWS 可用(尽管它可能并不总是最佳选择;它有非常强烈的观点),通常最好使用 @ConfigurationProperties
,或者至少使用构造函数注入,而不是在字段上使用 @Value
,后者具有字段注入的所有问题。
英文:
Spring knows how to map enums. Just use the enum value (not a fully-qualified name):
aws.s3.config.region: US_WEST_2
Note also that Spring Cloud AWS is available (though it may not always be the best choice; it has very strong opinions), and that in general it's better to use @ConfigurationProperties
or at a minimum constructor injection instead of @Value
on a field, which has all the pitfalls of field injection.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论