在spring引导的运行时访问特定的属性文件



我有一个spring-boot应用程序,我正在尝试将bean验证错误国际化。因此,我添加了包含验证消息的特定于区域设置的属性文件,并使用localresolver来更改区域设置。验证是区域设置更改工作正常。问题是验证消息Im还附加了字段名,例如:";付款人.toAddress.legalName"。为了获得更好的用户体验,我需要从正确的属性文件中获取该字段名的翻译。我如何实现读取键"的值的代码;付款人.toAddress.legalName";从ValidationMessages_XX.properties?XX代表验证器中设置的当前语言代码。

ConstraintViolation<ValidCustomer> constraintValidation = constraintViolations.stream().findFirst().get();
String invalidField = constraintValidation.getPropertyPath().toString();
String errorMsg = String.format("%s - %s", invalidField, constraintValidation.getMessage());

当应用程序启动时,您的文件将只读取一次。spring没有任何功能允许在运行时自动动态读取属性文件。

在这种情况下,如果您想动态读取它,您可以在应用程序运行时访问的数据库中移动该属性,也可以本机读取一些文件,但需要为其编写代码。

如果您只想读取一次,那么当应用程序启动时,以下代码将为您注入您期望使用的值。

使用@Value注释将值注入springbean 中

@Component <--- must be a component or anything else that spring registers as a bean
public class YourClass {
@Value("${payer.toAddress.legalName}")
String legalName;
}

最新更新