[英]valid not working spring boot when method is called from same class
My car model with bean validation我的车 model 带 bean 验证
@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.当我从 controller 调用 addCar 时,Valid 工作正常,但是当我从同一服务 class 中的方法调用它时,它没有验证汽车 Z20F35E630DAF44DBFA4C3F68F5399D8Z。
I'm calling addCars from controller我从 controller 打电话给 addCars
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.首先,您需要了解 spring 如何调用验证器。 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.
如果您查看 spring 验证启动器,您将看到它定义了 bean 后处理器,该处理器使用代理 object 包装所有使用有效注释注释的 bean,并添加了拦截具有有效参数的方法的方面。 So when validated bean/service is injected into dependant object, the proxy is injected instead.
因此,当将经过验证的 bean/service 注入依赖的 object 时,会改为注入代理。 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?
说了这么多,问自己一个问题:在哪个实例上调用 addCars 方法? Proxy or real bean?
代理还是真正的bean?
The problem here is that addCar method is not intercepted because is called directly by this
instance这里的问题是 addCar 方法没有被拦截,因为是
this
实例直接调用的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.