aspectj如何拦截以“find”开头的RooEntity的所有方法

时间:2014-06-04 20:54:32

标签: java spring aspectj spring-roo

我正在使用spring mvc和spring roo来完成我的项目。我有一个Roo实体如下:

@RooEntity
public class Post {
    ...
    public static Post findPostByUserAndCreateDate(User u, Calendar createDate) {

    }
    ...
}

现在,我想拦截我的项目中以" find"开头的所有方法。并使用@RooEntity注释类。我想围绕调用此方法编写代码。所以,我需要这样的东西:

@Aspect
public class FinderAspect {
    ...
    @Around(...I don't know what to put here....)
    public Object aroundFinders(ProceedingJoinPoint joinPoint) throws Throwable {
        //do something
        Object ret = joinPoint.proceed();
        //do something more
        return ret;
    }
...
}

请帮忙。感谢。

1 个答案:

答案 0 :(得分:0)

免责声明:我从未使用过Roo或Spring,但对AspectJ了解很多。所以我希望我能提供帮助。

模仿Roo的虚拟注释:

package org.springframework.roo.addon.entity;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface RooEntity {}

非实体样本类:

即使它有find*方法,也不应该匹配这个,因为它没有注释为@RooEntity

package de.scrum_master.app;

public class OtherClass {
    public String findLastName(String firstName) { return "Doe"; }
}

实体类+ main方法:

package de.scrum_master.app;

import org.springframework.roo.addon.entity.RooEntity;

@RooEntity
public class Application {
    public static void main(String[] args) {
        Application application = new Application();
        application.doSomething("test");
        application.findSomething("test");
        new OtherClass().findLastName("John");
        application.doSomethingElse();
        application.findSomethingElse(123);
    }

    private String doSomething(String string) { return string + "XX"; }
    private void findSomething(String string) {}
    private int doSomethingElse() { return 11; }
    public boolean findSomethingElse(int number) { return true; }
}

方面匹配实体方法find*

package de.scrum_master.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class FinderAspect {
    @Around("execution(* @org.springframework.roo.addon.entity.RooEntity *..find*(..))")
    public Object aroundFinders(ProceedingJoinPoint thisJoinPoint) throws Throwable {
        System.out.println(thisJoinPoint);
        // Do something
        Object ret = thisJoinPoint.proceed();
        // Do something else
        return ret;
    }
}

示例输出:

execution(void de.scrum_master.app.Application.findSomething(String))
execution(boolean de.scrum_master.app.Application.findSomethingElse(int))