java - Spring Boot 将 Java 注释上的配置属性/消息外部化

标签 java spring properties spring-boot annotations

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

var.foo="hello"

我可以使用

将它注入(inject)到 spring bean 中
@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 的 消息来源.

在后一种选择的情况下,您所要做的就是在 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了解更多详情。

关于java - Spring Boot 将 Java 注释上的配置属性/消息外部化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39107413/

相关文章:

java - CXF 生成的 WSDL 不包含 WS-SecurityPolicy 定义

java - Spring Boot中的外键问题-h2数据库

ios - 保留弧形属性

java - 链表/GUI toString()

java - 与 Guice 0 耦合获取多个新实例

java - 在排列的文本文件中搜索字符串

java - 将 Glassfish 3.1 更新到 4.0,应用程序失败并出现 NullpointerException

java - Spring JUnit 测试用例失败

properties - 选项、设置、属性、配置、首选项——何时以及为什么?

ios5 - Objective-C 2.0 中属性 "Synthesize"和 "Dynamic"的澄清