我正在尝试在使用 Spring Boot 2 构建的应用程序中使用不同的语言实现自定义消息。到目前为止,我已经使用 messages_br.properties
中设置的键为实体字段实现了它。现在,我正在尝试对 Controller 中抛出的异常消息进行相同的操作,但我不明白该怎么做。示例显示了太多我认为不是我需要的东西。
要配置文件,它位于我的 Application.java
中:
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource bundleMessageSource = new ReloadableResourceBundleMessageSource();
bundleMessageSource.setBasename("classpath:messages_br");
bundleMessageSource.setDefaultEncoding("UTF-8");
return bundleMessageSource;
}
@Bean
public LocalValidatorFactoryBean getValidator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
在每个字段上方的注释中,我可以指定如下内容:
@NotEmpty(message = "{beneficiary.name.notEmpty}")
private String name;
但是抛出的异常中的相同格式只会打印:
throw new InsufficientBalanceException("${user.balance.insufficientBalance}");
我几乎可以肯定,在学习如何实现异常时,我看到了一个类似的示例,但现在我找不到它了,也不记得它是如何完成的。
最佳答案
您可以使用@Value
创建错误消息属性,
@Value("${user.balance.insufficientBalance}")
private String insufficientBalance;
然后在Exception中使用它,
throw new InsufficientBalanceException(insufficientBalance);
如果您不想创建额外的属性,可以使用Environment
@Configuration
@PropertySource("file:messages_br.properties")
public class ApplicationConfiguration {
@Autowired
private Environment env;
public void getErrorMessage() {
env.getProperty("insufficientBalance");
}
//then use getErrorMessage
throw new InsufficientBalanceException(getErrorMessage);
}
}
希望有帮助。
关于java - 如何将 messages.properties 键发送到 Controller 中引发的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764154/