spring中自定義註解(annotation)與AOP中獲取註解
一、自定義註解(annotation)
自定義註解的作用:在反射中獲取註解,以取得註解修飾的類、方法或屬性的相關解釋。
package me.lichunlong.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//自定義註解相關設定
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
//自定義註解的屬性,default是設定預設值
String desc() default "無描述資訊";
}
二、自定義註解的使用
package me.lichunlong.spring.service;
import me.lichunlong.spring.annotation.LogAnnotation;
import me.lichunlong.spring.jdbc.JdbcUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
//與其它註解一樣的使用
@LogAnnotation(desc="this is UserService")
public void add() {
System.out.println("UserService add...");
}
}
三、AOP中獲取註解
// 環繞通知:類似與動態代理的全過程
// 攜帶引數ProceedingJoinPoint,且必須有返回值,即目標方法的返回
@Around(value = "execution(* me.lichunlong.spring.service.*.*(..)) &&
@annotation(log)")
public Object aroundMethod(ProceedingJoinPoint pjd,
LogAnnotation log
Object result = null;
System.out.println(log.desc());
try {
System.out.println("前置通知");
result = pjd.proceed();
System.out.println("後置通知");
} catch (Throwable e) {
System.out.println("異常通知");
}
System.out.println("返回通知");
return result;
}