1

I have a spring-boot:1.2.3 application and I'm having 2 validation issues:

  • it works in @Path endpoints but not @Service or @Component classes
  • it doesn't throw or log anything if the validation fails, it just returns a 400 without any additional information

These are the validation libraries that already come with spring-boot:1.2.3:

[INFO] |  +- org.hibernate:hibernate-validator:jar:5.1.3.Final:compile
[INFO] |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  +- org.glassfish.jersey.ext:jersey-bean-validation:jar:2.14:compile

These are the logging libraries that come with spring-boot-starter-log4j:

[INFO] +- org.springframework.boot:spring-boot-starter-log4j:jar:1.2.2.RELEASE:compile
[INFO] |  +- org.slf4j:slf4j-log4j12:jar:1.7.10:compile
[INFO] |  \- log4j:log4j:jar:1.2.17:compile

This validation works but doesn't log or show any stacktrace:

@Component
@Path("/validation-example")
public class ValidationExampleResource {

    @GET
    @Path("/{positiveNumber}")
    public int validationExample(@Min(0) @PathParam("positiveNumber") int positiveNumber) {
        ...
    }
}

But the validation doesn't work here at all:

@Service
public class ValidationExampleServiceImpl implements ValidationExampleService {

    @Override
    public int validationExample(@Min(0) int positiveNumber) {
        ...
    }
}
cahen
  • 15,807
  • 13
  • 47
  • 78

2 Answers2

1

Try this config. In my project it worked! Spring boot: 1.5.9.RELEASE

@Slf4j
@Service
@Validated
public class ValidationService {

    @Validated(CreateGroup.class)
    public void create(@Valid User user) {
        log.info("验证服务业务的作用");
    }

    public void basic(@NotNull(message = "名称不能为空") String name) {

    }

}

Details

VPK
  • 3,010
  • 1
  • 28
  • 35
percy0601
  • 11
  • 2
0

In order for the validation to work, you need to add @Valid

@Component
@Path("/validation-example")
public class ValidationExampleResource {

    @GET
    @Path("/{positiveNumber}")
    public int validationExample(@Valid @Min(0) @PathParam("positiveNumber") int positiveNumber) {
        ...
    }
}
Ian Lim
  • 4,164
  • 3
  • 29
  • 43
  • @cahen here is an example https://fbflex.wordpress.com/2014/06/02/spring-boot-recipe-reading-and-validating-lists-of-configuration-properties/ – Ian Lim Apr 25 '15 at 12:26