Spring AOP(Aspect Oriented Programming),即面向切面編程,是OOP(Object Oriented Programming,面向對象編程)的補充和完善。
OOP引入的核心概念包括:封裝,繼承和多態等;
AOP則可以深入到方法內部,在某個切入點或者切面處采取靜態”織入”的方式,在盡量不影響和改動原有代碼的基礎上,將新功能融入到原有的核心業務邏輯中。
在pom中引入依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
創建日志注解:
@Documented @Inherited //注解可被標注類的子類繼承 @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface TKLog { /** * 描述 */ String description() default ""; }
創建aop的處理器:
@Slf4j @Aspect @Component public class LogInterceptor { //標注切入點,即標有@TKLog的類 //@within:攔截被注解標注的類的所有方法,@annotation:攔截被注解的方法 @Pointcut("@within(com.tk.spring.aop.annotation.TKLog)") public void pointcut() { } //當標有@TKLog的類中的方法被調用前后,該方法會被執行 @Around("pointcut()") public void doExecute(ProceedingJoinPoint point) throws Throwable { log.info("方法即將執行:" + point.getSignature().getName()); Object result = point.proceed(); log.info("方法執行結束:" + result.toString()); } }
最后在需要的controller層中添加@TKLog注解以及啟動類加@EnableAspectJAutoProxy,就可以進行日志打印。