1

I have one maven spring project (as a library) and I am adding it as a dependency into spring maven project(web service). I have some properties files in both projects. In library there is one validationmessages.properties file.

I am using hibernate validator annotations on my model. For example,

@NotBlank(message = "{NotBlank-entityId}")
Private String entityId;

The class model which is in library,using as a request body in webservice, here library hibernate validation messages are not working in webservice. Here's the code:

Model: Task.java (In library)

public class Task {

@NotBlank(message = "{NotNull-EntityID}")
  private String entityId;

public String getEntityId() {
    return entityId;
  }

  public void setEntityId(final String entityId) {
    this.entityId = entityId;
  }
}

Taskvalidationmessages.properties (In library)

NotNull-EntityID = Entity ID can not be null.

TaskManagementConfiguration.java (In library)

@Configuration
@PropertySources({ @PropertySource("classpath:queries.properties"),
    @PropertySource("classpath:Taskvalidationmessages.properties") })
@Import(DataSourceConfiguration.class)
public class TaskManagementConfiguration {

}

TaskResource.java (Controller in webservice project)

@RequestMapping(value = WebserviceConstant.CREATE_TASK, method = RequestMethod.POST, produces = WebserviceConstant.APPLICATION_JSON)
  public ResponseEntity<CreateTaskResponse> createTask(
      @Valid @RequestBody final Task request,
      @RequestHeader(value = "access-token") final String accessToken) {

    return new ResponseEntity<CreateTaskResponse>(
        taskService.createTask(request, receivedToken), HttpStatus.CREATED);
  }

App.java (In Web service project)

@Configuration

@SpringBootApplication
@PropertySources({ @PropertySource("classpath:user-queries.properties") })

@Import({ TaskManagementConfiguration.class })
public class App {

  public static void main(final String[] args) {
    SpringApplication.run(App.class, args);
  }

}

Whenever I hit the resource url with empty value of entityId. It gives error like:

{
  "fieldErrors": [
    {
      "field": "entityId",
      "code": 200,
      "message": "{NotNull-EntityID}"
    }
  ]
} 
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
Kishori
  • 31
  • 7

1 Answers1

0

You need org.springframework.validation.beanvalidation.LocalValidatorFactoryBean

Add validator bean in your configurations (TaskManagementConfiguration)

@Bean(name = "messageSource")
public MessageSource messageSource()
{
    ReloadableResourceBundleMessageSource bean = new ReloadableResourceBundleMessageSource();
    bean.setBasename("classpath:Taskvalidationmessages");
    bean.setDefaultEncoding("UTF-8");
    return bean;
}

@Bean(name = "validator")
public LocalValidatorFactoryBean validator()
{
    LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
    bean.setValidationMessageSource(messageSource());
    return bean;
}
kuhajeyan
  • 10,727
  • 10
  • 46
  • 71