Action.java
//此注解只能修飾方法
@Target(ElementType.METHOD)
//當(dāng)前注解如何去保持
@Retention(RetentionPolicy.RUNTIME)
//生成到API文檔
@Documented
public @interface Action {
String name();
}
AopConfig.java
//JAVA配置類
@Configuration
//Bean掃描器
@ComponentScan("com.wangzhi.springboot.aop.test")
//開啟spring對(duì)aspectJ的支持
@EnableAspectJAutoProxy
public class AopConfig {}
這個(gè)類下的方法我們采用注解來攔截
@Service
public class DemoAnnotationService {
@Action( name = "注解式攔截的add操作")
public void add() {}
}
這個(gè)類下的方法我們采用方法規(guī)則來攔截
@Service
public class DemoMethodService {
public void add() {}
}
LogAspect.java
@Aspect
@Component
public class LogAspect {
//定義切面
@Pointcut("@annotation(com.wangzhi.springboot.aop.test.Action)")
public void annotationPointCut() {}
//聲明一個(gè)advice,并使用@pointCut定義的切點(diǎn)
@After("annotationPointCut()")
public void after(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//從切面中獲取當(dāng)前方法
Method method = signature.getMethod();
//得到了方,提取出他的注解
Action action = method.getAnnotation(Action.class);
//輸出
System.out.println("注解式攔截" + action.name());
}
//定義方法攔截的規(guī)則
@Before("execution(* com.wangzhi.springboot.aop.test.DemoMethodService.*(..))")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//攔截了方法
Method method = signature.getMethod();
//直接獲取方法名字
System.out.println("方法規(guī)則式攔截" + method.getName());
}
}
啟動(dòng)器
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
DemoMethodService methodService = context.getBean(DemoMethodService.class);
DemoAnnotationService annotationService = context.getBean(DemoAnnotationService.class);
annotationService.add();
methodService.add();
context.close();
}
}
pom.xml依賴
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>