Spring AOP註解
阿新 • • 發佈:2020-07-15
宣告切面類
@Aspect(切面):通常是一個類,裡面可以定義切入點和通知
配置切入點和通知
LogAdvice.java
package net.cybclass.sp.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component;//能被掃描 @Component //告訴Spring,這是一個切面類,裡面可以定義切入點和通知 @Aspect public class LogAdvice { //切入點表示式 @Pointcut("execution(* net.cybclass.sp.servicce.VideoServiceImpl.*(..))") public void aspect(){ } //前置通知 @Before("aspect()") public void beforeLog(JoinPoint joinPoint) { System.out.println("LogAdvice beforeLog 被呼叫了"); } //後置通知 @Before("aspect()") public void afterLog(JoinPoint joinPoint) { System.out.println("LogAdvice afterLog 被呼叫了"); } }
開啟Spring AOP註解配置
package net.cybclass.sp.aop; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.EnableAspectJAutoProxy;import org.springframework.stereotype.Component; //告訴Spring,這個類可以被掃描 @Component //掃描包 @ComponentScan("net.cybclass") @EnableAspectJAutoProxy //開啟了spring對aspect的支援 public class AnnotationConfig { }
VideoService.java
package net.cybclass.sp.servicce; import net.cybclass.sp.domain.Video; public interface VideoService { int save(Video video); Video findById(int id); }
VideoServiceImpl.java
package net.cybclass.sp.servicce; import net.cybclass.sp.domain.Video; import org.springframework.stereotype.Component; //@Component("videoService") //相當於配置bean的id @Component() //相當於配置bean的id public class VideoServiceImpl implements VideoService{ public int save(Video video) { System.out.println("儲存Video"); return 0; } public Video findById(int id) { System.out.println("根據id找視訊"); return new Video(); } }