Java Spring-Data-Rest 验证器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24318405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring-Data-Rest Validator
提问by Robert Greathouse
I have been trying to add spring validators to a spring-data-rest project.
我一直在尝试将 spring 验证器添加到 spring-data-rest 项目中。
I followed along and setup the "getting started" application via this link: http://spring.io/guides/gs/accessing-data-rest/
我跟随并通过此链接设置“入门”应用程序:http: //spring.io/guides/gs/accessing-data-rest/
...and now I am trying to add a custom PeopleValidator by following the documents here: http://docs.spring.io/spring-data/rest/docs/2.1.0.RELEASE/reference/html/validation-chapter.html
...现在我正在尝试按照此处的文档添加自定义 PeopleValidator:http://docs.spring.io/spring-data/rest/docs/2.1.0.RELEASE/reference/html/validation-chapter .html
My custom PeopleValidator looks like
我的自定义 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");
}
}
...and my Application.java class now looks like this
...我的 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();
}
}
I would expect that POSTing to the http://localhost:8080/people
URL would result in an error of some kind since the PeopleValidator is rejecting everything. However, no error is thrown, and the validator is never called.
我希望 POST 到http://localhost:8080/people
URL 会导致某种错误,因为 PeopleValidator 拒绝了所有内容。但是,不会抛出任何错误,并且永远不会调用验证器。
I have also tried manually setting up the validator as shown in section 5.1 of the spring-data-rest documentation.
我还尝试手动设置验证器,如 spring-data-rest 文档的第 5.1 节所示。
What am I missing?
我错过了什么?
采纳答案by Robert Greathouse
So it appears that the before/after "save" events only fire on PUT and PATCH. When POSTing, the before/after "create" events fire.
所以看起来之前/之后的“保存”事件只在 PUT 和 PATCH 上触发。发布时,“创建”事件之前/之后会触发。
I tried it the manual way again using the configureValidatingRepositoryEventListener
override and it worked. I'm not sure what I'm doing differently at work than here at home. I'll have to look tomorrow.
我使用configureValidatingRepositoryEventListener
覆盖再次以手动方式尝试它并且它起作用了。我不确定我在工作中所做的与在家中有何不同。明天我得看看。
I sure would love to hear if others have suggestions on why it wouldn't work.
我当然很想听听其他人是否有关于为什么它不起作用的建议。
For the record, here is what the new Application.java class looks like.
作为记录,这里是新的 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());
}
}
回答by Muel
A bit of a stab in the dark - I've not used spring-data-rest
. However, after having a read of the tutorial you're following, I think the problem is that you need a PersonValidator
not a PeopleValidator
. Rename everything accordingly:
在黑暗中有点刺 - 我没有使用过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");
}
}
Application
应用
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();
}
}
回答by Andreas
Looks like the feature is currently not implemented (2.3.0), unluckily there are no constants for the event names otherwise the solution below would not be that fragile.
看起来该功能目前尚未实现(2.3.0),不幸的是事件名称没有常量,否则下面的解决方案不会那么脆弱。
The Configuration
adds all properly named Validator
beans to ValidatingRepositoryEventListener
using the right event.
在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()));
}
}
}
回答by Amit
Another way of doing it is to use annotated handlers as specified here 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
Here is an example of how to use annotated handlers:
以下是如何使用带注释的处理程序的示例:
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");
}
}
Example is from githubedited for brevity.
示例来自为简洁起见编辑的github。