我是第一次使用AOP.我写了下面的AOP代码,当我用它来拦截一个特定的方法时它工作正常.
有人可以指导我 - 如何设置它来拦截某个包中的所有方法(com.test.model)?
基本上如何设置appcontext.xml.
另外,在调用每个方法之前,我是否需要执行类似下面的操作?
AopClass aoptest = (AopClass) _applicationContext.getBean("AopClass");
aoptest.addCustomerAround("dummy");
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
如果需要更多解释,请告诉我.
以下是我的代码:
接口:
package com.test.model;
import org.springframework.beans.factory.annotation.Autowired;
public interface AopInterface {
@Autowired
void addCustomerAround(String name);
}
Run Code Online (Sandbox Code Playgroud)
类:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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!");
}
}
Run Code Online (Sandbox Code Playgroud)
appcontext:
<!-- Aspect -->
<aop:aspectj-autoproxy />
<bean id="AopClass" class="com.test.model.AopClass" />
<bean id="TestAdvice" class="com.test.model.TestAdvice" />
Run Code Online (Sandbox Code Playgroud)
就放:
@Around("execution(* com.test.model..*.*(..))")
Run Code Online (Sandbox Code Playgroud)
执行表达式的格式为:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
Run Code Online (Sandbox Code Playgroud)
where only ret-type-pattern, name-patternandparam-pattern是必需的,所以至少我们需要一个表达式,如:
execution(ret-type-pattern name-pattern(param-pattern))
Run Code Online (Sandbox Code Playgroud)
ret-type-pattern匹配返回类型,*对于任何name-pattern匹配方法名称,您可以*用作通配符并..指示子包param-pattern匹配方法参数,(..)对于任意数量的参数您可以在此处找到更多信息:10. 使用 Spring 进行面向方面的编程,有一些有用的示例。
| 归档时间: |
|
| 查看次数: |
3104 次 |
| 最近记录: |