Spring 學習六 之 註解開發示例
阿新 • • 發佈:2018-12-22
- 需要一個Aspect 的類,在類上添加註解 @Aspect
package com.john.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint.StaticPart; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import com.john.service.LimintConfigService; @Component @Aspect public class LoggerAspect { @Pointcut(value ="execution(* com.john.service.LimintConfigService.*(..))") public void pointCut() { } @Before(value = "pointCut()") public void beforeAdvice() { System.out.println("before advice..."); } @After(value = "pointCut()") public void afterAdvice() { System.out.println("after advice..."); } @AfterReturning(value = "pointCut()") public void returningAdvice() { System.out.println("returning advice..."); } @AfterThrowing(value = "pointCut()") public void throwAdvice() { System.out.println("throw advice..."); } @Around(value = "pointCut()") public void aroundAdvice() { System.out.println("around advice..."); } }
- 業務邏輯類,在呼叫業務方法before()時,LoggerAspect 相應的通知,會切入到before()中,執行通知
@Service
public class LimintConfigService {
public void before() {
System.out.println("before()");
}
}
- 主配置類,簡化了,這裡主要測試 AOP 功能,所有簡化了很多,一定要開啟 aspect 功能,在配置類上面加註解 @EnableAspectJAutoProxy
@Configuration @EnableAspectJAutoProxy @ComponentScan(basePackages = {"com.john"}) public class MainConfig { }
- 測試
public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class); LimintConfigService service = context.getBean(LimintConfigService.class); service.after(); context.close(); }
- 執行結果,測試時,本人_遮蔽了 aroundAdvice()_ 通知
接下來,將詳細講解