从同一个类调用方法时,spring boot 无效 [英] valid not working spring boot when method is called from same class

查看:26
本文介绍了从同一个类调用方法时,spring boot 无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的带有 bean 验证的汽车模型

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;
    }

汽车服务

 @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()
  }

}

当我从控制器调用 addCar 时,Valid 工作正常,但是当我从同一个 Service 类中的方法调用它时,它没有验证 Car 模型.

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 .

我正在从控制器调用 addCars

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?

推荐答案

首先,您需要了解 spring 如何调用验证器.如果您查看 spring 验证启动程序,您将看到它定义了 bean 后处理器,该处理器将所有用有效注释注释的 bean 与代理对象包装在一起,并添加了拦截具有有效参数的方法的方面.所以当经过验证的 bean/service 被注入到依赖对象中时,代理被注入.然后当服务方法被调用时,调用被拦截,并为每个有效参数执行验证器.返回值也是如此.说了这么多,问自己一个问题:在哪个实例上调用 addCars 方法?代理还是真正的 bean?

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?

这里的问题是addCar方法没有被拦截,因为被this实例直接调用

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

这篇关于从同一个类调用方法时,spring boot 无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆