AOP:面向切面编程,提取重复代码,在指定方法执行前或执行后,动态切入其他方法到指定方法。
避免写大量重复代码,也易于维护。
常用AOP的框架之一:aspect J
@After、@Before、@Around定义建言(就是在方法哪个时候,前、后还是前后进行方法调用)
@PointCut:使切点复用
1、添加jar包:
<!-- spring-aop相关依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- aspectJ相关依赖 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency>
2、注解式拦截/方法;拦截
2.1、自定义注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Action {
String name();
}
2.2、使用注解拦截的类
@Service
public class DemoAnnotaionService {
@Action(name="注解式拦截的add操作")
public void add() {
}
}
2.3、使用方法拦截的类
@Service
public class DemoMethodService {
public void add() {
System.out.println("方法拦截的add()");
}
}
3、切面
@Aspect
@Component
public class LogAspect {
@Pointcut("@annotation(com.demo02.aop.Action)")
public void annotationPointCut() {
}
/**
* 先执行annotationPointCut()->@annotation(com.demo02.aop.Action)注解上的方法,
* 再执行after(JoinPoint joinPoint)方法。
* 方法上定义@after,当前方法后执行,拦截的方法先执行。
* 反之,定义@before,当前方法先执行,拦截的方法后执行。
* /
@After("annotationPointCut()")
public void after(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
Method method = signature.getMethod();
Action action = method.getAnnotation(Action.class);
System.out.println("2、注解式拦截"+action.name());
}
/**
* 先执行当前方法,后执行建言中的拦截方法。
* /
@Before("execution(* com.demo02.aop.DemoMethodService.*(..))")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
Method method = signature.getMethod();
System.out.println("3、方法规则拦截:"+method.getName());
}
}
@Aspect:表示当前类为一个切面
@Pointcut("@annotation(com.demo02.aop.Action)"):包含了@Action注解的方法进行拦截
@After("annotationPointCut()"):声明一个建言,并使用@PointCut定义的切点
@Before("execution(* com.demo02.aop.DemoMethodService.*(..))"):声明一个建言,此建言直接使用拦截规则做为参数
4、配置类
@Configuration
@ComponentScan("com.demo02.aop")
@EnableAspectJAutoProxy//开启spring对sapectJ的支持
public class AppConfig {
}
@EnableAspectJAutoProxy:开启spring对sapectJ的支持
5、运行
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
DemoAnnotaionService annotaionService = context.getBean(DemoAnnotaionService.class);
DemoMethodService methodService = context.getBean(DemoMethodService.class);
annotaionService.add();
methodService.add();
context.close();
}
}