之前一篇博客中写到了Spring AOP创建切面和通知,切面都很简单,没有参数,所通知的方法也没有参数,这里我们将会以一个计数器的例子(用切面记录每个数字被打印的次数),来说明切面如何访问和使用传递给被通知方法的参数。
代码中有详细注释
打印数字类 NumberPrinter.java
package com.aop;
import org.springframework.stereotype.Component;
@Component
public class NumberPrinter {
public void printNumber(int number){
System.out.println(number);
}
}
用来做计数器的切面 Counter.java
package com.aop;
import org.aspectj.lang.annotation.*;
import java.util.*;
@Aspect
public class Counter {
private Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//指定参数的切点
@Pointcut("execution( * com.aop.NumberPrinter.printNumber(int))" + "&& args(number)")
public void numPrinted(int number){}//声明带有参数的切点表达式
@Before("numPrinted(number)")//切点表达式
public void count(int number){//number参数来自切点方法
map.put(number, getCount(number) + 1);
}
public int getCount(int number){//获得该number被计数的次数
return map.containsKey(number) ? map.get(number) : 0;
}
}
配置类:
package com.aop;
import org.springframework.context.annotation.*;
@Configuration
@ComponentScan
@EnableAspectJAutoProxy//启用AspectJ注解的自动代理
public class Config {
@Bean
public Counter counter(){
return new Counter();
}
}
测试类:
package com.aop;
import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class CounterTest {
@Autowired//从SpringIOC容器中根据类型找到bean并注入
private NumberPrinter numberPrinter;
@Autowired
private Counter counter;
@Test//测试计数器
public void testCounter(){
numberPrinter.printNumber(1);
numberPrinter.printNumber(1);
numberPrinter.printNumber(2);
Assert.assertEquals(counter.getCount(1), 2);//断言测试结果的正确性
Assert.assertEquals(counter.getCount(2), 1);
}
}