gpt4 book ai didi

java - 使用 Spring AOP 拦截特定注解

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:27 26 4
gpt4 key购买 nike

我想看看以下情况是否可能,因为所有初步搜索都没有返回任何表明任何方式的信息。

我想使用 Hibernate 的 Validator 注释来验证 bean 方法,并且我想使用一些 AOP 框架(Spring、AOP Alliance、AspectJ 等)来拦截使用 Hibernate Validator 注释子集注释的方法(@NotNull@NotEmpty@Email 等);然后我希望 AOP 建议在遇到它们时运行。

这可以做到吗?如果是这样,我很难想象代码将如何工作。以Spring AOP的MethodInterceptor接口(interface)为例:

首先,使用 Hibernate Validator 的 bean:

public class SomeBean
{
private String data;

// Hibernate Validator annotation specifying that "data" cannot be an empty
// string.
@NotEmpty
public String getData() { ... } // etc.
}

然后,一些使用该 bean 的代码:

public void someMethod()
{
SomeBean oBean = new SomeBean();

// Validation should fail because we specified that "data" cannot be empty.
oBean.setData("");
}

接下来,当遇到 Hibernate Validator 带注释的方法时要运行的 AOP 建议。

public class ValidationInterceptor implements MethodInterceptor
{
public Object invoke(MethodInvocation invocation)
{
// Here's where we would use Hibernate's validator classes.
// My code example here is wrong, but it gets the point across.
Class targetClass = invocation.getClass(); // Should give me SomeBean.class
ClassValidator<targetClass> oValidator= new ClassValidator<targetClass>();

// Here I need to get a reference to the instance of the offending
// SomeBean object whose data has been set to empty...not sure how!
SomeBean oOffendingBean = getTheBadBeanSomehow();

InvalidValue[] badVals = oValidator.getInvalidValues(oOffendingBean);
}
}

所以,我不仅对 Spring AOP(切入点定义等)配置拦截我想要的 Hibernate Validator 注释感到窒息,而且我不仅没有完全掌握如何实现实际的建议(例如,如何从建议中实例化有问题的 SomeBean ,正如我在上面的评论中提到的),而且我什至不确定这个解决方案是否可能,Spring 或其他。

提前感谢您在正确方向上的一些温和的“插入”!

最佳答案

您可能对 method validation 感兴趣Hibernate Validator 4.2 引入的功能,提供对验证方法参数和返回值的支持。

然后您可以使用 Seam Validation它将此功能与 CDI 集成。如果你想将方法验证与 Spring 一起使用,你可以看看 this GitHub 上的项目,展示了如何将方法验证功能与 Spring AOP 集成(免责声明:我是该项目以及 Seam Validation 的作者)。

为了使您的示例正常工作,您必须使用 @NotEmpty 注释 setter 方法的参数,如下所示:

public class SomeBean {

private String data;

@NotEmpty
public String getData() { return data; }

public void setData(@NotEmpty String data) { this.data = data; }

}

关于java - 使用 Spring AOP 拦截特定注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7814184/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com