maven依赖:
org.springframework.boot
spring-boot-starter-aop
一、自定义注解
import java.lang.annotation.*;
@Documented
@Inherited
@Target({ ElementType.FIELD, ElementType.METHOD ,ElementType.TYPE_USE,ElementType.ANNOTATION_TYPE,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisHandel {
String key() default "";
String keyField() default "username";
}
二、创建AOP基于注解方式(这里只演示环绕通知,环绕通知可以阻塞方法体的运行)
@Aspect
@Configuration
public class RedisAspect {
//
//定义切点方法
@Pointcut("@annotation(com.ethendev.wopihost.annotation.RedisHandel)")
public void pointCut(){}
//环绕通知
@Around("pointCut()")
public void around(ProceedingJoinPoint joinPoint) {
try{
//1.获取到所有的参数值的数组
Object[] args = joinPoint.getArgs();
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
//2.获取到方法的所有参数名称的字符串数组
String[] parameterNames = methodSignature.getParameterNames();
Method method = methodSignature.getMethod();
System.out.println("---------------参数列表开始-------------------------");
for (int i =0 ,len=parameterNames.length;i < len ;i++){
System.out.println("参数名:"+ parameterNames[i] + " = " +args[i]);
}
System.out.println("---------------参数列表结束-------------------------");
RedisHandel redis=(RedisHandel)method.getAnnotation(RedisHandel.class);
System.out.println("自定义注解 key:" + redis.key());
System.out.println("自定义注解 keyField:" + redis.keyField());
Class cla=method.getClass();
if(cla.isAnnotationPresent(RedisHandel.class)){
RedisHandel redisHandel =(RedisHandel)cla.getAnnotation(RedisHandel.class);
String key=redisHandel.key();
String keyField=redisHandel.keyField();
System.out.println("key = " + key);
System.out.println("keyField = " + keyField);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
三、service层中使用(注意 自定义注解失效可能你的bean或方法未纳入spring范围)
比如:
@Service
public class Test {
@RedisHandel(key = "kkkk" ,keyField = "param1")
public String test(String abc,int i8,int i2, String str ,Integer i){
return "1";
}
}
@GetMapping("/hello")
public String hello(){
//这个会失效
meTest("德玛西亚",1);
//这个通过Autowird service层的方法就不会失效 @Autowired Test test;
test.test("德邦总管",1,2,"德玛西亚皇子",3);
return "hello";
}
@RedisHandel(key = "kkkk" ,keyField = "param1")
private void meTest(String str ,Integer i){
System.out.println(str);
System.out.println(i);
}
以下为测试效果:
总结:如果你的注解在启动类加了@EnableAspectJAutoProxy 配置文件加了
spring.aop.proxy-target-class=true注解依旧无效的话,可能就是注解用的方法存在注解无法被spring管理的原因。