简体   繁体   中英

Spring boot validation not working for all beans

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) {
        ...
    }
}

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

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) {
        ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM