cahen
cahen

Reputation: 16676

Spring boot validation not working for all beans

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

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

Upvotes: 1

Views: 2865

Answers (2)

percy0601
percy0601

Reputation: 11

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

Upvotes: 1

Ian Lim
Ian Lim

Reputation: 4284

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

Upvotes: 0

Related Questions