如何将非字符串值(枚举/类)分配给 application.properties?

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年10月8日 08:50:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64254274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定