本节目的:初步介绍AOP,以及编写一个简单的AOP实例。
1.AOP基本概念
2. 简单实例
-----------------------------------------------------------分割线-------------------------------------------------------------
1. 概念
故事背景:例如开一场演唱会,当演唱会到了精彩之处的时候,观众会进行鼓掌;可能演唱会过程中会出现中断等不可预知事件。
(1) 通知(加强)advice: Aop框架在切入点前后执行的处理,一般有3类5中,before ,after,around,其中after中有三种(after、after-returning、after-throwing),比如演唱会精彩点后,观众会鼓掌--这个精彩点对观众来讲就是一个通知。
(2) 连接点 joinpoint : 应用执行过程中能够插入切面的一个点,这个点可以调用方法时、抛出异常时、甚至修改一个字段时。结合上面演唱会的例子,那就是“精彩之处”的时候,精彩点就是链接点。精彩点后面就可以插入切面。
(3) 切入点pointCut: 就是插入可以Advice的连接点,简单可以理解为advice定义了切面的“什么”和“何时”,切点定义了“何处”。一个切点可以匹配通知一个或者多个连接点。
(5) 织入weaving: 将advice增加到目标对象中,合成一个加强版的对象。这样就是整个AOP完成的功能。
2. 简单实例
(2)首先创建一MusicPerform类:
package com.learn.spring.aop;
public class MusicPerform{
public void perform() {
System.out.println("performaing.......");
}
}
(2)创建一个观众切面,当执行perform的时候进行切入:
package com.learn.spring.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class Audience {
@Before("execution(** com.learn.spring.aop.MusicPerform.perform())")
public void silencephone(){
System.out.println("close cell phone!");
}
}
(3)然后通过java装配:
package com.learn.spring.aop;
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
@EnableAspectJAutoProxy
@ComponentScan
public class Myconfig {
@Bean
public Audience audience(){
return new Audience();
}
@Bean
public MusicPerform musicPerform1(){
MusicPerform musicPerform = new MusicPerform();
return musicPerform;
}
}
(4)执行代码:
package com.learn.spring.aop;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MusicTest {
public static void main(String[] args) {
@SuppressWarnings("resource")
AnnotationConfigApplicationContext ctx = (AnnotationConfigApplicationContext) new AnnotationConfigApplicationContext(
Myconfig.class);
MusicPerform musicPerform = (MusicPerform) ctx.getBean("musicPerform1");
musicPerform.perform();
}
}
查看执行结果: