簡體   English   中英

Spring Boot 應用程序的內部化

[英]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.propertiesmessages_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM