Spring boot externalize config properties/messages on Java annotations

Bharath :

Is there a way to read text from external properties file in spring without using the @Value annotation. Ex: application.properties

var.foo="hello"

I can inject it in a spring bean using

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

as a class variable. Is there a way to include this property without using the @Value annotation. Something like how JSR bean validation does.

@NotNull(message={custom.notnull})

and you externalize this property value in ValidationMessages.properties file.

Example, if I have a resource(web component) class, and if I have to use Swagger annotations to document them,

@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");
    }
}

and the model,

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

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

How do you externalize this string/sentences/messages to an external properties file. I think this applies to general Java annotations and spring and not specific to Swagger. The reason I specified Swagger is, if just like hibernate validation Java library has the option of specifying these messages in an external ValidationMessages.properties file and spring knows by default to pick it up (or can be configured).

Does Swagger provide such an option? If it does not, how do I setup one?

Underlying problem is, I don't want to clutter my code/logic with documentation related data(meta data).

Thomas Kåsene :

I don't think you can achieve this unless the underlying implementation of the annotations you're using either come with their own standard for i18n (like ValidationMessages.properties), or support Spring's MessageSource.

In the case of the latter alternative, all you should have to do is to add your key/value pairs inside a messages.properties file and let the framework do the rest:

messages.properties

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

SomeClass.java

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

Bottom line is, depending on the framework you're trying to use, it may or may not support this out-of-the-box.

Now, as far as Swagger goes, i18n support for documentation was proposed as a new feature, but it was shut down or put on hold while they put some more thought into how it should be implemented. See https://github.com/OAI/OpenAPI-Specification/issues/274 for more details.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=454917&siteId=1