@AspectJ注解配置切面编程(注解方式)

搭建环境

新建web项目 spring4_day03_annotation , 引入依赖
pom.xml

<!-- spring核心依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		
		<!-- springaop相关包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
		</dependency>

		<!-- 单元测试 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- 日志 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
		</dependency>
		
		<!-- spring集成测试 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.3.13.RELEASE</version>
		</dependency>

同时导入
applicationContext.xml,
log4j.properties到工程

第一步: 编写目标对象 (bean)、spring容器、测试类

(1):创建接口CustomerService.java

第二步: 编写通知,配置切面

1) 编写通知类,在通知类 添加@Aspect 注解,代表这是一个切面类,并将切面类交给spring管理(能被spring扫描到@Component)。
@Component(“myAspect”):将增强的类交给spring管理,才可以增强
@Aspect:将该类标识为切面类(这里面有方法进行增强),相当于<aop:aspect ref=”myAspect”>

前置通知

在切面的类MyAspect.java类中添加通知方法@Before(),
方案一:可以直接将切入点的表达式写到@Before()中

	//前置通知
	//相当于:<aop:before method="before" pointcut="bean(*Service)"/>
    //@Before("bean(*Service)"):参数值:自动支持切入点表达式或切入点名字
	@Before("bean(*Service)")
	public void before(JoinPoint joinPoint){
		System.out.println("=======前置通知。。。。。");
	}

方案二:可以使用自定义方法,使用@Pointcut 定义切入点
切入点方法的语法要求:
切点方法:private void 无参数、无方法体的方法,方法名为切入点的名称
一个通知方法@Before可以使用多个切入点表达式,中间使用“||”符合分隔,用来表示多个切入点

    //自定义切入点
	//方法名就是切入点的名字
	//相当于<aop:pointcut expression="bean(*Service)" id="myPointcut"/>
	@Pointcut("bean(customerService)")
	private void myPointcut(){}
	//自定义切入点
	//方法名就是切入点的名字
	//相当于<aop:pointcut expression="bean(*Service)" id="myPointcut2"/>
	@Pointcut("bean(productService)")
	private void myPointcut2(){}
	
	
	//前置通知
	//相当于:<aop:before method="before" pointcut-ref="myPointcut"/>
	//相当于:<aop:before method="before" pointcut-ref="myPointcut2"/>
	@Before("myPointcut()||myPointcut2()")
	public void before(JoinPoint joinPoint){
		System.out.println("=======前置通知。。。。。");
	}

后置通知

在切面的类MyAspect.java类中添加通知方法

环绕通知

在切面的类MyAspect.java类中添加通知方法

抛出通知

在切面的类MyAspect.java类中添加通知方法

最终通知

在切面的类MyAspect.java类中添加通知方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值