你們都知道spring最大的特色就IOC和AOP,IOC是最經常使用的注入,就是被注入的類上加@Component註解,在須要用到時候,經過 @Autowired注入,不用每次都
new
出來。固然爲了分清層級,@Component一般使用@Repository、@Service、@Controller代替。
本文只要記錄AOP的用法,以springboot框架爲例。spring
我的理解AOP就是攔截器,(多是我理解不全面,反正我如今就認爲它是攔截器,攔截器!攔截器!只不過娶個英文名字而已)。
功能:AOP能夠在作某些事情以前或以後強塞一些操做。數組
我知道的有兩種實現方法,路徑切入和註解切入,區別在於切點,二者各有利弊,前者適合批量切入,後者比較靈活,加註解的類纔會被切。springboot
一、經過路徑切入
二、經過註解切入框架
一、新建切面類上面加倆註解 @Aspect @Component 缺一不可
二、@Pointcut寫上要切入的包,也能夠精確到類
三、@Before切入點以前要處理的業務
四、@After切入點以後要處理的業務code
@Aspect @Component public class VisitAop { @Pointcut("execution(public * com.forum.controller.*.*(..))") public void log() { } @Before("log()") public void doBefore(JoinPoint joinPoint) { ........ } @After("log()") public void doAfter() { ........ } }
一、自定義註解
二、切入類@Aspect @Component 缺一不可
三、@Pointcut寫上要切入註解(意思是帶此註解者,必切!)
四、@Before、@After同上。get
一、自定義註解
1.1 @Target和@Retention定義自定義註解,無需其餘,標識做用的註解。同步
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface VisitCount { }
三、切入點
3.1和路徑切入的區別在此博客
@Pointcut("@annotation(com.Annotation.VisitCount)")
此外能夠了解一些doBefore(),的參數JoinPoint,以便操做業務;it
一、joinPoint.getSignature().getDeclaringType().getSimpleName(),切入的類名
二、joinPoint.getArgs(),切入方法的參數數組
三、joinPoint.getSignature().getName(),切入方法名io
個人博客即將同步至騰訊雲+社區,邀請你們一同入駐:https://cloud.tencent.com/dev...