JAVA關於AOP切面的測試

//定義切面

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.After;
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;
 
@Aspect
@Component
public class LogIntercept{
      
    @Pointcut("execution(public * com.xwood.test.action.*Action.*(..))")
    public void actionLog(){}
      
      
    @Before("actionLog()")
    public void before() {
        this.printLog(" @Before  actionLog() 準備打印action層日誌...  ");
    }
      
    @Around("actionLog()")
    public void around(ProceedingJoinPoint pjp) throws Throwable{
        this.printLog(" @Around  actionLog() 準備打印action層日誌... ");
        pjp.proceed();
        this.printLog(" @Around  actionLog() action層邏輯已經執行完成  ");
    }
      
      
    @After("actionLog()")
    public void after() {
        this.printLog(" @After  actionLog() action層邏輯已經執行完成  ");
    }
      
      
    private void printLog(String str){
        System.out.println(str);
    }
     

}

 

//切換所環繞的方法

import org.springframework.stereotype.Controller;
 
@Controller
public class UserAction{
     
    public void   login(){
        System.out.println("  【UserAction】 用戶登錄 ... ");
    }
 

}

 

 

//測試用例方法

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
 
import com.xwood.test.action.UserAction;
 
@ContextConfiguration(locations={"classpath*:spring-*.xml"})
public class ActionLogTest extends  AbstractJUnit4SpringContextTests {
     
    @Autowired
    private  UserAction action;
     
    @Test
    public  void   test() throws Exception{
        action.login();
    }
 

}

 

 

//控制檯日誌

 @Around  actionLog() 準備打印action層日誌... 
 @Before  actionLog() 準備打印action層日誌...  
  【UserAction】 用戶登錄 ... 
 @Around  actionLog() action層邏輯已經執行完成  
 @After  actionLog() action層邏輯已經執行完成

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章