欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring实战+总结归纳:AOP导学图+实例

程序员文章站 2022-05-21 23:29:06
...

一、思维导图

Spring实战+总结归纳:AOP导学图+实例

二、构建AOP步骤

1.导包:AOP,Aspect

        <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>

2.在Java配置文件中开启代理

@EnableAspectJAutoProxy

3.编写切面(包括切点和通知)

package com.yan.otl.main.aspect;

import org.aspectj.lang.annotation.After;
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;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class LoginControllerAspect {
	
	@Pointcut("execution(* com.yan.otl.main.controller.LoginController.getUser(..))")
	public void getUser() {}
	
	@Before("getUser()")
	public void before() {
		System.out.println("---------------------前置通知");
	}
	
	@After("getUser()")
	public void after() {
		System.out.println("---------------------后置通知,返回通知和异常通知");
	}
	
	@AfterReturning("getUser()")
	public void afterReturning() {
		System.out.println("---------------------返回通知");
	}
	
	@AfterThrowing("getUser()")
	public void afterThrowing() {
		System.out.println("---------------------异常通知");
	}
}

4、输出结果

---------------------前置通知
aaa@qq.com
---------------------后置通知,返回通知和异常通知
---------------------返回通知