使用注解与Java配置的Aop示例
0,添加所需依赖
<dependency>
<groupId>${spring-groupId}</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
1,自定义注解类:@Action
/**
* 拦截规则的注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
String name();
}
2,用于演示注解拦截的类:ShowAnnotationService
/**
* 使用注解的被拦截类
*/
@Service
public class ShowAnnotationService {
@Action(name = "注解式拦截的add操作")
public void add(){}
}
3,用于演示被方法规则拦截的类:ShowMethodService
/**
* 使用方法规则的被拦截类
* 在add上没有声明@Action注解
*/
@Service
public class ShowMethodService {
public void add(){}
}
4,切面类,定义拦截后的操作
/**
* 切面
*/
@Aspect
@Component
public class LogAspect {
@Pointcut("@annotation(com.zyf.Action)")
public void annotationPointCut(){
}
@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("注解式拦截:"+action.name());
}
@Before("execution(* com.zyf.ShowMethodService.*(..))")
public void before(JoinPoint joinPoint){
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
System.out.println("方法规则拦截:"+method.getName());
}
}
5,Java配置的配置类
@Configuration
@ComponentScan("com.zyf")
@EnableAspectJAutoProxy
public class AopConfig {
}
6,测试
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AopConfig.class);
ShowAnnotationService annotationService = context.getBean(ShowAnnotationService.class);
ShowMethodService methodService = context.getBean(ShowMethodService.class);
annotationService.add();
methodService.add();
context.close();
}
}
7,测试结果