Spring-数据-静止验证器

nafvub8i  于 2023-10-15  发布在  Spring
关注(0)|答案(5)|浏览(150)

我一直在尝试将spring验证器添加到spring-data-rest项目中。
我跟着沿着,并通过这个链接设置“入门”应用程序:http://spring.io/guides/gs/accessing-data-rest/
.现在我正尝试按照以下文档添加自定义PeopleValidator:http://docs.spring.io/spring-data/rest/docs/2.1.0.RELEASE/reference/html/validation-chapter.html
我的自定义PeopleValidator看起来像

package hello;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class PeopleValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    public void validate(Object target, Errors errors) {
        errors.reject("DIE");
    }
}

.我的Application.java类现在看起来像这样

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;

@Configuration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public PeopleValidator beforeCreatePeopleValidator() {
        return new PeopleValidator();
    }
}

我希望POST到http://localhost:8080/people URL会导致某种错误,因为PeopleValidator拒绝了所有内容。但是,不会抛出错误,也不会调用验证器。
我也尝试过手动设置验证器,如spring-data-rest文档的5.1节所示。
我错过了什么?

a0zr77ik

a0zr77ik1#

因此,看起来之前/之后的“保存”事件只在PUT和PATCH上触发。POST时,将触发before/after“create”事件。
我尝试了手动方式再次使用configureValidatingRepositoryEventListener覆盖和它的工作。我不知道我在工作和在家里有什么不同。我明天再看。
我当然很想听听其他人是否有关于为什么它不起作用的建议。
为了记录在案,下面是新的Application.java类的样子。

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.core.event.ValidatingRepositoryEventListener;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;

@Configuration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Application extends RepositoryRestMvcConfiguration {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
        validatingListener.addValidator("beforeCreate", new PeopleValidator());
    }
}
bq3bfh9z

bq3bfh9z2#

看起来这个功能目前还没有实现(2.3.0),不幸的是没有事件名称的常量,否则下面的解决方案不会那么脆弱。
Configuration使用正确的事件将所有正确命名的Validator bean添加到ValidatingRepositoryEventListener

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.event.ValidatingRepositoryEventListener;
import org.springframework.validation.Validator;

@Configuration
public class ValidatorRegistrar implements InitializingBean {

    private static final List<String> EVENTS;
    static {
        List<String> events = new ArrayList<String>();
        events.add("beforeCreate");
        events.add("afterCreate");
        events.add("beforeSave");
        events.add("afterSave");
        events.add("beforeLinkSave");
        events.add("afterLinkSave");
        events.add("beforeDelete");
        events.add("afterDelete");
        EVENTS = Collections.unmodifiableList(events);
    }

    @Autowired
    ListableBeanFactory beanFactory;

    @Autowired
    ValidatingRepositoryEventListener validatingRepositoryEventListener;

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Validator> validators = beanFactory.getBeansOfType(Validator.class);
        for (Map.Entry<String, Validator> entry : validators.entrySet()) {
            EVENTS.stream().filter(p -> entry.getKey().startsWith(p)).findFirst()
                    .ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue()));
        }
    }
}
3yhwsihp

3yhwsihp3#

有点戳在黑暗中-我没有使用spring-data-rest。然而,在阅读了你所遵循的教程之后,我认为问题在于你需要一个PersonValidator而不是一个PeopleValidator。相应地检查所有内容:

PersonValidator

package hello;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class PersonValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    public void validate(Object target, Errors errors) {
        errors.reject("DIE");
    }
}

申请

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;

@Configuration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public PersonValidator beforeCreatePersonValidator() {
        return new PersonValidator();
    }
}
dba5bblo

dba5bblo4#

另一种方法是使用这里指定的带注解的处理程序http://docs.spring.io/spring-data/rest/docs/2.1.0.RELEASE/reference/html/events-chapter.html#d5e443
下面是一个如何使用带注解的处理程序的示例:

import gr.bytecode.restapp.model.Agent;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.HandleBeforeSave;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.stereotype.Component;

@Component
@RepositoryEventHandler(Agent.class)
public class AgentEventHandler {

    public static final String NEW_NAME = "**modified**";

    @HandleBeforeCreate
    public void handleBeforeCreates(Agent agent) {
            agent.setName(NEW_NAME);
    }

    @HandleBeforeSave
    public void handleBeforeSave(Agent agent) {
        agent.setName(NEW_NAME + "..update");
    }
}

示例来自github,为简洁起见进行了编辑。

dluptydi

dluptydi5#

我猜spring-data-rest是基于Spring Data PersistentEntity构建的,直接应用验证可能不容易(针对模型对象的验证信息)。
您可能需要执行以下操作才能进行请求验证:
1.创建一个bean validator工厂来创建JSR-303 bean validator(如果你还没有的话):
public class StringName {

@Bean
LocalValidatorFactoryBean localValidatorFactoryBean() {
    return new LocalValidatorFactoryBean();
}

}
1.添加bean验证器
@Component @ RedArgsConstructor public class CustomizedRepositoryRestConfiguration实现了RepositoryRestConfigurer {

private final LocalValidatorFactoryBean validator;

@Override
public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener v) {
    v.addValidator("beforeCreate", validator);
    v.addValidator("beforeSave", validator);
    v.addValidator("beforeLinkSave", validator);
}

}

相关问题