Spring中使用注解自定义切面
1.定义注解
package com.spring;
import java.lang.annotation.*;
/**
* 注解
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SpringAnnotation {
String value() default "";
}
ElementType
| 类型 | 说明 |
|---|---|
| TYPE | 类、接口(包括注释类型)或枚举声明 |
| FIELD | 字段声明(包括枚举常量) |
| METHOD | 方法声明 |
| PARAMETER | 参数声明 |
| CONSTRUCTOR | 构造方法声明 |
| LOCAL_VARIABLE | 局部变量声明 |
| ANNOTATION_TYPE | 注释类型声明 |
| PACKAGE | 包声明 |
RetentionPolicy
| 类型 | 说明 |
|---|---|
| SOURCE | Annotation信息仅存在于编译器处理期间,编译器处理完之后就没有该Annotation信息了 |
| CLASS | 编译器将Annotation存储于类对应的.class文件中。默认行为 |
| RUNTIME | 编译器将Annotation存储于class文件中,并且可由JVM读入 |
2.切面的实现
package com.spring;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* Aspect 实现
*/
@Aspect
@Component
public class SpringAspect {
private static final Logger logger = LoggerFactory.getLogger(SpringAspect.class);
/**
* 初始化
*/
@Pointcut("@annotation(com.spring.SpringAnnotation)")
public void springAnnotation() {
}
@Around("springAnnotation() && @annotation(annotation)")
public Object aroundInit(ProceedingJoinPoint point, SpringAnnotation annotation) throws Throwable {
MethodSignature ms = (MethodSignature) point.getSignature();
Method method = ms.getMethod();
Object returnValue = handleAnnotation(point, annotation, method);
return returnValue;
}
/**
* 处理切面
*
* @param point
* @param annotation
* @param method
* @return
* @throws Throwable
*/
private Object handleAnnotation(ProceedingJoinPoint point, SpringAnnotation annotation, Method method) throws Throwable {
logger.info("before invoke method");
String value = annotation.value();
logger.info("value on annotation:{}", value);
Object obj = point.proceed(point.getArgs());
logger.info("after invoke method");
return obj;
}
}
3.客户端使用
package com.spring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 客户端
*/
public class AspectClient {
private static final Logger logger = LoggerFactory.getLogger(AspectClient.class);
public static void main(String[] args) {
AspectClient client = new AspectClient();
client.handleMethod();
}
/**
* 业务逻辑
*/
@SpringAnnotation(value = "client")
public void handleMethod() {
logger.info("handle method");
}
}
提示:需要在Spring的环境中运行