繁体   English   中英

Spring启动在Java注释上外部化配置属性/消息

[英]Spring boot externalize config properties/messages on Java annotations

有没有办法在不使用@Value注释的情况下从spring中读取外部属性文件中的文本。 例如:application.properties

var.foo="hello"

我可以用弹簧豆注入它

@Value("${var.foo}") String value;

作为类变量。 有没有办法在不使用@Value注释的情况下包含此属性。 类似于JSR bean验证的方式。

@NotNull(message={custom.notnull})

并在ValidationMessages.properties文件中外部化此属性值。

例如,如果我有一个资源(Web组件)类,并且我必须使用Swagger注释来记录它们,

@controller
@path("/")
@Api(description = "User Resource API")
public class UserResource {

    @Path("/users")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "returns user details", notes = "some notes")
    public User getUser() {

        return new User(123, "Joe", "Montana");
    }
}

和模型,

@ApiModel("user model")
public class User {

    @ApiModelProperty(value = "This represents user id")
    private String id;
    private String firstName;
    private String lastName;
    ...
}

如何将此字符串/句子/消息外部化为外部属性文件。 我认为这适用于一般的Java注释和spring,而不是Swagger特有的。 我指定Swagger的原因是,如果像hibernate验证一样,Java库可以选择在外部ValidationMessages.properties文件中指定这些消息,并且spring默认知道它可以获取(或者可以配置)。

Swagger提供这样的选择吗? 如果没有,我该如何设置?

根本问题是,我不想把我的代码/逻辑与文档相关的数据(元数据)混为一谈。

除非您使用的注释的底层实现带有自己的i18n标准(如ValidationMessages.properties ),或者支持Spring的MessageSource ,否则我认为您无法实现此目的。

在后一种替代方案中,您应该做的就是在messages.properties文件中添加键/值对,让框架完成剩下的工作:

messages.properties

my.validation.error.message=Something went terribly wrong!

SomeClass.java

@MySpringCompatibleValidationAnnotation("my.validation.error.message")
private String someVariable;

底线是,根据您尝试使用的框架,它可能支持也可能不支持这种开箱即用的功能。

现在,就Swagger而言,i18n对文档的支持被​​提议作为一项新功能,但它被关闭或暂停,同时他们更多地考虑应该如何实现它。 有关详细信息,请参阅https://github.com/OAI/OpenAPI-Specification/issues/274

使用@Value("${property}")注释来注入配置属性有时会很麻烦,所以spring boot引入了@ConfigurationProperties ,这应该是你想要的解决方案。

是参考文档。

在配置文件中声明bean时,可以使用占位符。您可以尝试一个示例: https ://www.mkyong.com/spring/spring-propertyplaceholderconfigurer-example/

如果您使用的是Spring Boot,那么您可以尝试这种方法,而无需进行任何特殊配置

@environment.getProperty('property')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM