有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring验证在服务层级别不起作用

我有一个Spring Boot项目(2.3.3),我想验证服务层方法输入参数。所以在我的pom里。我添加的xml

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

因为它不再是父母的一部分。接下来是我的服务方法接口和实现服务方法。我的实现服务用@Validated注释,我的方法如下

public void deleteGreetingById(@NotNull(message = "greetingId must not be null.")Integer greetingId) {

我还了解到,验证仅在默认情况下绑定到控制器层。因此,为了在服务层启用它,我添加了一个PostValidationProcessor

@Configuration
public class MethodValidationConfig {

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }
}

当我现在以null作为输入参数执行测试时,不会发生任何事情,也不会引发异常。当我这么做的时候

 Assert.notNull(greetingId,"greetingId must not be null"); 

在方法内部,会像预期的那样抛出InvalidParameterException。但我更喜欢基于注释的验证,因为作为输入参数的整个类对象的@Valid validation

有人能解释为什么没有触发验证吗

编辑:

@RestController
public class GreetingsConsumerController {

    private final GreetingsService greetingsService;

    public GreetingsConsumerController(GreetingsService greetingsService) {
        this.greetingsService = greetingsService;
    }

    @PostMapping(value = "/greetings", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Greeting createGreeting( @RequestBody @Valid GreetingDto greetingDto){
        return greetingsService.addGreeting(greetingDto);
    }

    @GetMapping(value = "/greetings/{id}")
    public Greeting getGreetingById(@PathVariable Integer id){
        return greetingsService.findGreetingById(id);
    }

    @GetMapping(value = "/greetings")
    public List<Greeting> getAllGreetings(){
        return greetingsService.findAllGreetings();
    }

    @DeleteMapping(value = "/greetings/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteGreetingById(@PathVariable Integer id){

        greetingsService.deleteGreetingById(id);
    }
}

接口:

public interface GreetingsService {
    
        Greeting findGreetingById(Integer greetingId);
        List<Greeting> findAllGreetings();
        Greeting addGreeting( GreetingDto greetingDto);
        void deleteGreetingById( Integer greetingId);
    
    }

IterfaceImpl:

@Service
@Validated
public class GreetingsServiceImpl implements GreetingsService {

.
.
.
       @Override
        public void deleteGreetingById(@NotNull(message = "greetingId must not be null. ") Integer greetingId) {
            ...
        }

}

我还将Bean添加到我的Springboot应用程序中,但仍然没有引发异常

@SpringBootApplication
public class GreetingsConsumerApplication {

    public static void main(String[] args) {

        SpringApplication.run(GreetingsConsumerApplication.class, args
        );
    }
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }

}

共 (0) 个答案