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

Bha*_*ath 11 java spring annotations properties spring-boot

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

var.foo="hello"
Run Code Online (Sandbox Code Playgroud)

我可以用弹簧豆注入它

@Value("${var.foo}") String value;
Run Code Online (Sandbox Code Playgroud)

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

@NotNull(message={custom.notnull})
Run Code Online (Sandbox Code Playgroud)

并在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");
    }
}
Run Code Online (Sandbox Code Playgroud)

和模型,

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

    @ApiModelProperty(value = "This represents user id")
    private String id;
    private String firstName;
    private String lastName;
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Tho*_*ene 6

我不认为你可以实现这个目标,除非你正在使用的注释的底层实现或者带有他们自己的i18n标准(比如ValidationMessages.properties),或者支持Spring的MessageSource.

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

messages.properties

my.validation.error.message=Something went terribly wrong!
Run Code Online (Sandbox Code Playgroud)

SomeClass.java

@MySpringCompatibleValidationAnnotation("my.validation.error.message")
private String someVariable;
Run Code Online (Sandbox Code Playgroud)

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

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