1. 程式人生 > >AOP 切面的使用,以及如何在通知上獲取切入方法的註解和引數

AOP 切面的使用,以及如何在通知上獲取切入方法的註解和引數

1、自定義註解

@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.METHOD)
public @interface AdviceAnnotation {

	String name();
}

2、service層

public interface AdviceService {

	void study(String name) throws Exception;
}

3、實現類

@Service
public class AdviceServiceImpl implements AdviceService {

	
	@AdviceAnnotation(name = "我是註解name!!!")
	public void study(String name) throws Exception {
		System.out.println("好好學習,天天向上");
		
		throw new Exception("my god!!");
	}

}

4、切面

@Aspect       // 切面註解
@Component
public class StudyAdvice {

	@Before(value = "execution(* com.teng.advice.service.impl.AdviceServiceImpl.study(..))"
            + "&& args(name)",argNames="name")
    private void studyBefore(String name){
        System.out.println(String.format("獲取到的引數:%s", name));    // 獲取切入方法上的引數
        System.out.println("學習之前先打局遊戲!");
    }
	
	@After(value="@annotation(com.teng.advice.annotation.AdviceAnnotation) &&"
			+ "execution(* com.teng.advice..*.*(..))")
	private void studyAfter(AdviceAnnotation ad){
		
		System.out.println("學累了再打局遊戲!");
	}
	
	@Around("execution(* com.teng.advice..*.*(..)) && @annotation(ad)")
	private Object studyAround(ProceedingJoinPoint pjp,AdviceAnnotation ad) throws Throwable{    // 環繞通知需要有返回值
		System.out.println("前置通知:還是打遊戲");
		System.out.println(String.format("註解name:%s", ad.name()));    // 獲取切入方法上的註解
		Object result =  pjp.proceed();
		System.out.println("後置通知:依舊打遊戲");
		return result;
	}
	
	
	@AfterThrowing(pointcut="execution(* com.teng.advice..*.*(..))",throwing="ex")
	private void studyThrow(Throwable ex){
		System.out.println(ex.getMessage());
	}

       // @AfterReturning(returning="rvt" ,pointcut="execution(* com.teng.advice..*.*(..))")          
       // public void test(Object rvt){        
       //        System.out.println("獲取目標方法返回值:" + rvt);         
       //  }  

 }

5、執行

@SpringBootApplication
public class BootTestApplication 
{
    public static void main( String[] args )
    {
        SpringApplication.run(BootTestApplication.class, args);
    }
    
    @Autowired 
    private AdviceService adviceService;
    
    @PostConstruct
    public void init() throws Exception{
    	adviceService.study("小耿");
    }
}


6、列印結果

前置通知:還是打遊戲
註解name:我是註解name!!!
獲取到的引數:小耿
學習之前先打局遊戲!
好好學習,天天向上
學累了再打局遊戲!
my god!!