Spring引导在Java注释上外部化配置属性/消息
有没有办法在spring从外部属性文件中读取文本而不使用@Value
注释。 例如:application.properties
var.foo="hello"
我可以用弹簧豆注入它
@Value("${var.foo}") String value;
作为类变量。 有没有办法在不使用@Value
注释的情况下包含此属性。 类似于JSR beanvalidation的方式。
@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的原因是,如果像hibernatevalidation一样,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;
底线是,根据您尝试使用的框架,它可能支持也可能不支持这种开箱即用的function。
现在,就Swagger而言,i18n对文档的支持被提议作为一项新function,但它被关闭或暂停,同时他们更多地考虑应该如何实现它。 有关详细信息,请参阅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')
- 检测/validationSD卡驱动器
- Eclipse WTP:对于项目中定义的类,JSP文件中的“导入___无法解决”错误
- JSP Unterminated
带嵌套OGNL的标记 - 从文件读取双精度时输入不匹配
- Arrays.asList()。contains()on Double vs double arrays
- Collections.synchronizedList()方法有什么用? 它似乎没有同步列表
- 公开@Asynchronous函数的当前进度以在View中使用
- 在不使用条件代码的情况下确定数字是奇数还是偶数
- POST期间REST Web服务中的HTTP 400错误,FormParam包含自己的对象(例如enities)