简体   繁体   中英

Custom Spring Validator Doesn't Get Injected

The problem is this: Using Spring Boot, I have a hibernate entity (Message) and I want to create a custom validator for it.

import org.springframework.validation.Validator;
        
@Component
public class MessageValidator implements Validator {
@Override
    public boolean supports(Class<?> clazz) {
        return Message.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
    ... Do work here ...
    }
}

Then, I have a service

@Service
public class MessagesService {

    @Autowired
    Validator validator;

    public void doSomething(Message m) {
        Errors e = new BeanPropertyBindingResult(new Object(), "dummy");
        this.validator.validate(m, e);
    }
}

The problem is that the call to this.validator.validate(m, e); never makes it to my implementation.

My pom.xml has (amongst others):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

So, am I missing something glaringly obvious here? If I name the validator component and I qualify the reference in the service, it's all good. But I'm expecting the Spring wiring to provide the proper validator for the type of object I call for. Or is this expectation too much?

Problem must be with your Autowiring.

Since you are using interface here, it could autowire the default (one of the implementation provided by Spring) instance.

  @Autowired
  Validator validator;

Solution:

  1. Use MessageValidator instead of Validator
    @Autowired
    MessageValidator validator;

OR 2. Use qualified name:

    @Autowired
    @Qualifier(value = "messageValidator") //note lowercase m
    Validator validator;

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