如何包装实体数据并传递给spring验证器 [英] How to wrap the entity data and pass to the spring validator
问题描述
我正在尝试将实体数据与其他一些信息(例如请求者信息)包装在一起.现在,我有以下代码,
I am trying to wrap the entity data with some other information such as requestor info. Right now, I have the following code,
public class EntityController {
@Autowired
private EntityValidator entityValidator;
...
@InitBinder("entity")
protected void initBinder(WebDataBinder binder) {
binder.addValidators(entityValidator);
}
}
我的验证人就像
public class EntityValidator implements Validator {
@Override
public boolean supports(Class<?> clz) {
return Entity.class.equals(clz);
}
@Override
public void validate(Object obj, Errors errors) {
...
}
}
对于传递到validate方法中的Object参数,现在是Entity类对象.就像我说的那样,我想要一个包装了该实体类对象的自定义对象.这可能吗?如果是,该怎么做?请帮忙.非常感谢.
For the Object parameter passed into the validate method is the Entity class object now. As I said, I want a customized object with this entity class object wrapped in. Is that possible? If yes, how to do that? Please help. Many thanks.
推荐答案
如果我正确理解,您希望Entity
实例成为另一个类的成员(一个包装了该实体类对象的自定义对象).这样的事情怎么样:
If I understand correctly, you want the Entity
instance to be a member of another class (a customized object with this entity class object wrapped in). How about something like this:
public interface EntityHolder {
Entity getEntity();
}
您可以通过多种方式实现(自定义对象):
Which you can implement (the customized object) in a number of ways:
public class RequestorInfo implements EntityHolder {
private final long requestorId;
public Entity getEntity() { ... }
}
public class CustomObject2 implements EntityHolder {
public Entity getEntity() { ... }
}
然后像这样使用验证器:
And then use the validator like this:
public class EntityValidator implements Validator {
@Override
public boolean supports(Class<?> clz) {
return EntityHolder.class.isAssignableFrom(clz);
}
@Override
public void validate(Object obj, Errors errors) {
EntityHolder holder = (EntityHolder) obj;
// validate the entity obtained by holder.getEntity()
}
}
请注意,在supports
方法中将equals
更改为isAssignableFrom
.这使您可以传递EntityHolder
的子类.
Notice the equals
was changed to isAssignableFrom
in the supports
method. This enables you to pass in a subclass of EntityHolder
.
这篇关于如何包装实体数据并传递给spring验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!