Spring中Advice简单案例

不讲概念,只看代码

1、配置类

@Configuration//配之类
@EnableAspectJAutoProxy//启用AspectJ自动代理
@ComponentScan(basePackages = {"spring01","spring02"}) //basePackages指定扫描的包
public class Config {
}

2、切面类

@Aspect
@Component
public class Audience {
    /**
     * 相当于访问相同报下的不同的类,他们拥有相同的包路径,可以定义一个变量
     */
    @Pointcut("execution(* spring02.aspect.Performance.perform(..))")
    public void performance(){
    }

    @Before("performance()")
    public void silenceCellPhones(){
        System.out.println("====表演前将手机调静音");
    }

    @Before("performance()")
    public void takeSeats(){
        System.out.println("====表演前就做");
    }

    @AfterReturning("performance()")
    public void applause(){
        System.out.println("====表演后鼓掌");
    }

    @AfterThrowing("performance()")
    public void demandRefund(){
        System.out.println("====表演失败时退款");
    }
    @Around("performance()")
    public void  watchPerformance(ProceedingJoinPoint point){
        try {
            System.out.println("====观看前1");
            point.proceed();
            System.out.println("====观看后2");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}

3、被通知对象接口

public interface Performance {
    void perform();
}

4、被通知对象实现类

@Component("performance")
public class PerformanceImpl implements Performance{
    @Override
    public void perform() {
        System.out.println("======表演开始=====");
    }
}

5、测试类

@RunWith(SpringJUnit4ClassRunner.class)//启动测试时创建Spring上下文
@ContextConfiguration(classes = {Config.class})//配置文件对象
public class TestClass {
    @Autowired
    private Performance performance;
    @Test
    public void test(){
        performance.perform();
    }
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值