[英]How to send a messages.properties key to an exception being thrown in a controller?
I am trying to implement custom messages with a different language in my application built with Spring Boot 2. So far I have implemented it for entities' fields using keys set in messages_br.properties
. 我正在尝试在使用Spring Boot 2构建的应用程序中使用另一种语言来实现自定义消息。到目前为止,我已经使用
messages_br.properties
设置的键为实体字段实现了它。 Now, I'm trying the same with exception messages thrown in controllers, but I don't understand how to do it. 现在,我正在尝试对控制器中引发的异常消息进行相同的操作,但是我不知道该怎么做。 Examples show too much of things I believe is not what I need.
例子显示了我认为不是我需要的太多东西。
To configure the file, this is in my Application.java
: 要配置文件,这是在我的
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;
}
In the annotations above each field, I can specify something like this: 在每个字段上方的注释中,我可以指定以下内容:
@NotEmpty(message = "{beneficiary.name.notEmpty}")
private String name;
But the same format in a thrown exception prints that only: 但是在抛出的异常中使用相同的格式只能打印出以下内容:
throw new InsufficientBalanceException("${user.balance.insufficientBalance}");
I'm almost sure that when learning how to implement exceptions I saw a similar example but now I cannot find it anymore nor I remember how it is done. 我几乎可以肯定,在学习如何实现异常时,我看到了一个类似的示例,但是现在我找不到了,也不记得它是如何完成的。
You can create a property for error message with @Value
, 您可以使用
@Value
创建错误消息的属性,
@Value("${user.balance.insufficientBalance}")
private String insufficientBalance;
And then use it in Exception, 然后在Exception中使用它,
throw new InsufficientBalanceException(insufficientBalance);
If you don't want to create extra property, you can use Environment
如果您不想创建额外的属性,则可以使用
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);
}
}
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.