在Spring Boot应用程序中的国际化

huangapple go评论134阅读模式
英文:

Internalization in Spring Boot Application

问题

抱歉,我无法执行您的请求,但我可以为您提供翻译。以下是您提供的代码和内容的翻译:

抱歉,我的英语可能有些不好。我正在开发一个Spring Boot应用程序,遇到了以下情况。我已经实现了国际化,并创建了以下配置类:

@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.propertiesmessages_us.properties

我定义了一个用户实体类如下:

@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) {
//代码...
}

如果验证失败,我可以正确地获得所有错误消息。

{
  "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) {
//代码...
}

我无法获得翻译后的错误消息。

{
  "timestamp": 1599169130869,
  "status": 400,
  "error": "Not validate field",
  "message": [
    "roles {not.empty.field}",
    "birthday {not.empty.field}"
  ],
  "path": "/api/v1/users"
}

有人知道这是什么问题吗?谢谢。

英文:

Sorry for my english. I am working on a spring boot application and I have the following situation. I implemented internalization and I created a following configuration class

@EnableWebMvc
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {   

  @Bean
    public LocaleResolver localeResolver() {
        AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
        localeResolver.setDefaultLocale(new Locale(&quot;es_ES&quot;));
        return localeResolver;
    }  
   
    @Bean
    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(resourceBundleMessageSource());
        return bean;
    }

    
    @Bean(&quot;messageSource&quot;)
    public MessageSource resourceBundleMessageSource() {
        ReloadableResourceBundleMessageSource messageSource
                = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename(&quot;classpath:messages&quot;);
        messageSource.setDefaultEncoding(&quot;UTF-8&quot;);
        return messageSource;
    }
    

}

Also I have two properties files messages.properties and messages_us.properties.

And I defined a User entity class like this:

@Entity
@Table(name = &quot;users&quot;, uniqueConstraints = @UniqueConstraint(columnNames = &quot;email&quot;))
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {    

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = &quot;id&quot;, table = &quot;users&quot;, nullable = false)
    private Long id;

    @NotEmpty(message = &quot;{not.field.empty}&quot;)
    @NotNull(message = &quot;{not.field.empty}&quot;)
    @Column(name = &quot;name&quot;)
    private String name;

    @Column(name = &quot;lastname&quot;, table = &quot;users&quot;, nullable = false, length = 100)
    private String lastname;

    @Column(name = &quot;birthday&quot;, table = &quot;users&quot;)
    @Temporal(TemporalType.DATE)
    @NotNull(message = &quot;birthday {not.empty.field}&quot;)
    private Date birthday;

}

When I try to test validation by calling following endpoint

    @PostMapping(&quot;/users&quot;)
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity&lt;?&gt; createUser(@Valid @RequestBody User user) {
//code...
}

If validation failes, I'm getting all error messages correctly.

{
    &quot;timestamp&quot;: 1599168856694,
    &quot;status&quot;: 400,
    &quot;error&quot;: &quot;Not validate field&quot;,
    &quot;message&quot;: [
        &quot;birthday Obligatory filed&quot;
    ],
    &quot;path&quot;: &quot;/api/v1/users&quot;
}

But when I use @Valid in a Service class like this

    @Override
    @Transactional()
    public User saveUser(@Valid User user) { 
//code...
}

I don't get the translated messages error messages.

{
    &quot;timestamp&quot;: 1599169130869,
    &quot;status&quot;: 400,
    &quot;error&quot;: &quot;Not validate field&quot;,
    &quot;message&quot;: [
        &quot;roles {not.empty.field}&quot;,
        &quot;birthday {not.empty.field}&quot;
    ],
    &quot;path&quot;: &quot;/api/v1/users&quot;
}

Does anybody knows what's the issue here?
Thanks

答案1

得分: 0

假设你的saveUser服务方法只从REST API端点方法"createUser"中被调用,该方法已经在验证了USER实体。我认为在服务方法的参数中使用@Valid 是没有必要的,因为REST端点已经做了必要的工作。

这篇文章可能对你有帮助 - https://auth0.com/blog/exception-handling-and-i18n-on-spring-boots-apis/

英文:

Assuming your saveUser service method is getting called only from the REST API endpoint method "createUser" which is already validating the USER entity. I do not see any need for using @Valid in the service method argument as well. The rest endpoint is already doing the needful.

This post might help you - https://auth0.com/blog/exception-handling-and-i18n-on-spring-boots-apis/

huangapple
  • 本文由 发表于 2020年9月4日 06:45:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63732600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定