2015年3月30日 星期一

spring aopaspectj

package com.lfo.suntone.aspect;

import java.io.IOException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import com.lfo.suntone.NotValidException;
import com.lfo.suntone.controller.StockController;
import com.lfo.suntone.dao.DaoUtilsInterface;
import com.lfo.suntone.tool.AspectTool;
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Aspect
@Component

public class ControllerAspect {
    @Autowired
    private DaoUtilsInterface daoUtils;
  
    @Autowired
    private  AspectTool aspectTool;
    @Pointcut("execution(* com.lfo.suntone.controller.StockController.*(..))")
    public void header() {
      
    }
    @Around("header()")
    public Object   header(ProceedingJoinPoint  j) throws NotValidException {
      
      
      
      
         if(aspectTool.isValidUserid(j)){
             try {
          
                 System.out.println("header isValidUserid:");
                 daoUtils.insertHistory();
                Object ss = j.proceed();//不但攔截並且取回結果
                return ss  ;//必須回傳否則無法原方法return 為null

            } catch (Throwable e) {
                e.printStackTrace();
            }
         }else{
             System.out.println("header isnot  ValidUserid");
            
             StockController s=(StockController) j.getTarget();
             try {
                s.getResponse().getOutputStream().print("error userid");
            } catch (IOException e) {
              
                e.printStackTrace();
            }
             return null;
            
            
            
         }
        return null;
    }
}

沒有留言:

張貼留言