Spring AOP 处理通知中的参数【Spring 入门】

之前一篇博客中写到了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);
    }
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值