简体   繁体   中英

valid not working spring boot when method is called from same class

My car model with bean validation

@Document(collection = "Cars")
    public class Car {

        public static final String NAME = "car";
        @Id
        private String id;

        @NotBlank(message = "Brand name should n't be empty")
        @CsvBindByName(column = "Car Brand")
        private String brand;

        @NotBlank(message = "Model name should n't be empty")
        @CsvBindByName(column = "Car Model")
        private String model;
    }

Car service

 @Service
    @Validated
    public class CarServices {

        @Autowired
        CarRepo repo;

        public Car addCar(@Valid Car car, String traceId) {
              //save to repo
         }

    }
 public HashMap<String, Object> addCars(MultipartFile file, String traceId) {

         //reading csv and passing each car object to addCar   
       Call to addCar()
  }

}

When I'm calling addCar from controller Valid is working fine,But when I'm calling it from method which is in the same Service class it is not validating Car model.

I'm calling addCars from controller

How to solve this?What should I do to make that work? What changes I have to make in code?

First, you need to understand how spring invokes validators. If you look at spring validation starter, you will see that it defines bean post processor that wraps all beans annotated with valid annotation with proxy object and adds aspects that intercepts methods with valid parameters. So when validated bean/service is injected into dependant object, the proxy is injected instead. Then when the service method is called, the call is being intercepted and validators are executed for every valid parameter. The same happens for return value. Having said this, ask yourself the question: on which instance you call addCars method? Proxy or real bean?

The problem here is that addCar method is not intercepted because is called directly by this instance

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