与Spring AOP的拦截方法只使用注释 [英] Intercepting method with Spring AOP using only annotations

查看:467
本文介绍了与Spring AOP的拦截方法只使用注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Spring上下文文件我有这样的事情:

In my Spring context file I have something like this:

<bean id="userCheck" class="a.b.c.UserExistsCheck"/>
<aop:config>
      <aop:aspect ref="userCheck">
         <aop:pointcut id="checkUser"
                expression="execution(* a.b.c.d.*.*(..)) &amp;&amp; args(a.b.c.d.RequestObject)"/>
         <aop:around pointcut-ref="checkUser" method="checkUser"/>
      </aop:aspect>
</aop:config>    

a.b.c.UserExistsCheck看起来是这样的:

a.b.c.UserExistsCheck looks like this:

@Aspect
public class UserExistsCheck {

@Autowired
private UserInformation userInformation;

public Object checkUser(ProceedingJoinPoint pjp) throws Throwable {
    int userId = ... //get it from the RequestObject passed as a parameter
    if (userExists(userId)) {
        return pjp.proceed();
    } else {
        return new ResponseObject("Invalid user);
    }
}

和正在被这个东西截获类看起来是这样的:

And the class that is being intercepted with this stuff looks like this:

public class Klazz {
    public ResponseObject doSomething(RequestObject request) {...}
}

这工作。该呼叫被传递到Klazz之前根据需要UserExistCheck被执行。问题是,这是我得到了它的工作的唯一途径。要使用注释,而不是背景文件得到这个工作似乎只是太多我的小大脑。所以...究竟应该怎么做注解,UserExistsCheck和Klazz的方法呢?而且我还需要别的东西吗?另一类?一些仍然在上下文文件?

This works. UserExistCheck is executed as desired before the call is passed to Klazz. The problem is that this is the only way I got it working. To get this working by using annotations instead of the context file seems to be just too much for my small brain. So... how exactly should I annotate the methods in UserExistsCheck and Klazz? And do I still need something else too? Another class? Still something in the context file?

推荐答案

是否启用注解基于AOP?在<一个href=\"http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-aspectj-support\"相对=nofollow>文档说,你必须添加

Have you enabled annotation-based AOP? The documentation says you have to add

<aop:aspectj-autoproxy/>

要Spring配置。然后,你需要在你的 checkUser 方法前加一个注解。它看起来像你想要 @Around 咨询,说明<一个href=\"http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-ataspectj-around-advice\"相对=nofollow>这里。

to your spring configuration. Then you need to add an annotation in front of your checkUser method. It looks like you want @Around advice, as described here.

@Aspect
public class UserExistsCheck {

  @Around("execution(* a.b.c.d.*.*(..)) && args(a.b.c.d.RequestObject)")
  public Object checkUser(ProceedingJoinPoint pjp) throws Throwable {

这篇关于与Spring AOP的拦截方法只使用注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆