[英]Internalization in Spring Boot Application
对不起我的英语不好。 我正在开发一个 spring 启动应用程序,我有以下情况。 我实现了内部化并创建了以下配置类
@EnableWebMvc
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(new Locale("es_ES"));
return localeResolver;
}
@Bean
@Override
public Validator getValidator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(resourceBundleMessageSource());
return bean;
}
@Bean("messageSource")
public MessageSource resourceBundleMessageSource() {
ReloadableResourceBundleMessageSource messageSource
= new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
}
另外我有两个属性文件messages.properties
和messages_us.properties
。
我定义了一个 User 实体类,如下所示:
@Entity
@Table(name = "users", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", table = "users", nullable = false)
private Long id;
@NotEmpty(message = "{not.field.empty}")
@NotNull(message = "{not.field.empty}")
@Column(name = "name")
private String name;
@Column(name = "lastname", table = "users", nullable = false, length = 100)
private String lastname;
@Column(name = "birthday", table = "users")
@Temporal(TemporalType.DATE)
@NotNull(message = "birthday {not.empty.field}")
private Date birthday;
}
当我尝试通过调用以下端点来测试验证时
@PostMapping("/users")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<?> createUser(@Valid @RequestBody User user) {
//code...
}
如果验证失败,我会正确收到所有错误消息。
{
"timestamp": 1599168856694,
"status": 400,
"error": "Not validate field",
"message": [
"birthday Obligatory filed"
],
"path": "/api/v1/users"
}
但是当我在这样的Service
类中使用 @Valid 时
@Override
@Transactional()
public User saveUser(@Valid User user) {
//code...
}
我没有收到翻译的消息错误消息。
{
"timestamp": 1599169130869,
"status": 400,
"error": "Not validate field",
"message": [
"roles {not.empty.field}",
"birthday {not.empty.field}"
],
"path": "/api/v1/users"
}
有人知道这里有什么问题吗? 谢谢
假设您的 saveUser 服务方法仅从已经验证 USER 实体的 REST API 端点方法“createUser”中调用。 我也认为不需要在服务方法参数中使用 @Valid 。 其余端点已经在做需要的事情。
这篇文章可能对您有所帮助 - https://auth0.com/blog/exception-handling-and-i18n-on-spring-boots-apis/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.