복붙노트

[SPRING] 스프링 데이터 레스트 검사기

SPRING

스프링 데이터 레스트 검사기

나는 spring-data-rest 프로젝트에 spring validator를 추가하려고 노력해왔다.

나는이 링크를 통해 "시작"응용 프로그램을 따라 갔다. 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();
    }
}

나는 PeopleValidator가 모든 것을 거부하기 때문에 http : // localhost : 8080 / people URL로 POST하는 것이 어떤 종류의 오류를 일으킬 것이라고 예상한다. 그러나 오류가 발생하지 않으며 발리 데이터가 호출되지 않습니다.

또한 spring-data-rest 문서의 5.1 절에 표시된대로 유효성 검사기를 수동으로 설정하려고 시도했습니다.

내가 뭘 놓치고 있니?

해결법

  1. ==============================

    1.따라서 이전 / 이후의 "저장"이벤트는 PUT 및 PATCH에서만 실행됩니다. 게시 할 때 이전 / 이후 "만들기"이벤트가 발생합니다.

    따라서 이전 / 이후의 "저장"이벤트는 PUT 및 PATCH에서만 실행됩니다. 게시 할 때 이전 / 이후 "만들기"이벤트가 발생합니다.

    나는 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());
        }
    }
    
  2. ==============================

    2.해당 기능이 현재 구현되지 않은 것처럼 보입니다 (2.3.0). 불행하게도 이벤트 이름에 대한 상수가 없으면 아래 해결 방법이 취약하지 않을 것입니다.

    해당 기능이 현재 구현되지 않은 것처럼 보입니다 (2.3.0). 불행하게도 이벤트 이름에 대한 상수가 없으면 아래 해결 방법이 취약하지 않을 것입니다.

    Configuration은 올바른 이벤트를 사용하여 적절하게 명명 된 모든 Validator 빈을 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()));
            }
        }
    }
    
  3. ==============================

    3.어둠 속의 약간의 찌르기 - 저는 스프링 데이터를 사용하지 않았습니다. 그러나 다음 튜토리얼을 읽은 후에는 문제는 PeopleValidator가 아닌 PersonValidator가 필요하다는 것입니다. 그에 따라 모든 이름 바꾸기 :

    어둠 속의 약간의 찌르기 - 저는 스프링 데이터를 사용하지 않았습니다. 그러나 다음 튜토리얼을 읽은 후에는 문제는 PeopleValidator가 아닌 PersonValidator가 필요하다는 것입니다. 그에 따라 모든 이름 바꾸기 :

    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();
        }
    }
    
  4. ==============================

    4.이를 수행하는 또 다른 방법은 여기에 지정된 주석 처리기를 사용하는 것입니다 http://docs.spring.io/spring-data/rest/docs/2.1.0.RELEASE/reference/html/events-chapter.html#d5e443

    이를 수행하는 또 다른 방법은 여기에 지정된 주석 처리기를 사용하는 것입니다 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에서 가져온 것입니다.

  5. from https://stackoverflow.com/questions/24318405/spring-data-rest-validator by cc-by-sa and MIT license