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

心不动则不痛 提交于 2020-06-29 03:42:11

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/62376233/valid-not-working-spring-boot-when-method-is-called-from-same-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!