包中所有方法的 AOP

AOP for all methods in a package

我是第一次使用AOP。 我写了下面的 AOP 代码,当我用它来拦截特定方法时,它工作正常。

有人可以指导我 - 如何设置它以拦截特定包中的所有方法 (com.test.model)?

基本上如何设置appcontext.xml。

另外,在调用每个方法之前,我是否需要像下面这样调用?

AopClass aoptest = (AopClass) _applicationContext.getBean("AopClass");
aoptest.addCustomerAround("dummy");

有人可以帮忙吗?

如果需要更多解释,请告诉我。

下面是我的代码:

接口:

package com.test.model;

import org.springframework.beans.factory.annotation.Autowired;

public interface AopInterface {


    @Autowired
    void addCustomerAround(String name);
}

Class:

package com.test.model;

import com.test.model.AopInterface;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class AopClass implements AopInterface {

    public void addCustomerAround(String name){
        System.out.println("addCustomerAround() is running, args : " + name);
    }
}

AOP:

package com.test.model;

import java.util.Arrays;

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



@Aspect
public class TestAdvice{


     @Around("execution(* com.test.model.AopInterface.addCustomerAround(..))")
       public void testAdvice(ProceedingJoinPoint joinPoint) throws Throwable {

        System.out.println("testAdvice() is running!");


       }
}

appcontext:

<!-- Aspect -->
    <aop:aspectj-autoproxy />
    <bean id="AopClass" class="com.test.model.AopClass" />
    <bean id="TestAdvice" class="com.test.model.TestAdvice" />

只需输入:

@Around("execution(* com.test.model..*.*(..))")

执行表达式的格式为:

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)

只有 ret-type-patternname-patternparam-pattern 是必需的,所以至少我们需要这样的表达式:

execution(ret-type-pattern name-pattern(param-pattern))
  • ret-type-pattern 匹配 return 类型,* 匹配任何
  • name-pattern匹配方法名,可以用*通配,..表示分包
  • param-pattern匹配方法参数,(..)匹配任意数量的参数

您可以在此处找到更多信息:10. Aspect Oriented Programming with Spring, there are some useful examples