spring: 使用Aspectj代理EnabelAspectjAutoProxy

本文介绍如何利用Spring AOP特性,在不修改原始业务代码的情况下为音乐会场景添加额外的行为,如观众入场、鼓掌等。通过定义切点、前置通知和后置通知,实现了对Performance类方法的增强。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用JavaConfig的话,可以在配置类的类级别上通过使用EnableAspectJ-AutoProxy注解启用自动代理功能。

package ch2.test;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class Audience {

	
	//定义命名的切点
	@Pointcut("execution(** ch2.test.Performance.perform(..))")
	public void Performance(){}
	
	//表演开始之前:关闭手机
	@Before("Performance()")
	public void silenCellPhones()
	{
		System.out.println("silen cell phones");
	}
	
	//表演开始之前:入座
	@Before("Performance()")
	public void takingSeats()
	{
		System.out.println("take seats");
	}
	
	//表演开始之后:鼓掌
	@AfterReturning("Performance()")
	public void applause()
	{
		System.out.println("clap clap clap");
	}
	
	//表演结束之后:表演失败退票
	@AfterThrowing("Performance()")
	public void demandRefund()
	{
		System.out.println("demand refund");
	}
	
}

  

config

package ch2.test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan
//声明自动代理: 开启自动代理
@EnableAspectJAutoProxy
public class ConcertConfig {

	@Bean
	public Audience audience()
	{
		return new Audience();
	}
}

  

 

转载于:https://www.cnblogs.com/achengmu/p/8315778.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值