日期:2014-05-17  浏览次数:20764 次

基于@AspectJ使用Spring AOP
[list=1]
  • 在spring的xml配置文件中配置aspectj
  • 如下:
    <aop:aspectj-autoproxy />
    
  • 创建注释的定义
  • 如下:
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface AroundPointCut {
    	boolean accessRead() default false;
    }
    
  • 声明切面、声明切入点、拦截对目标对象方法调用
  • 如下:
    <bean id="loggerAspect" class="com.aspect.AroundAspect"></bean>
    

    @Aspect // 声明切面
    public class AroundAspect {
    
    	// 声明切入点
    	@Pointcut("execution(@com.crane.aspect.AroundPointCut public * * (..))")
    	public void aroundPointCut() {
    
    	}
    
    	// 拦截对目标对象方法调用
    	@Around("com.crane.aspect.LoggerAspect.aroundPointCut()")
    	public Object doLoggerPointCut(ProceedingJoinPoint jp) throws Throwable {
    		// 获取连接点的方法签名对象
    		MethodSignature joinPointObject = (MethodSignature) jp.getSignature();
    		// 连接点对象的方法
    		Method method = joinPointObject.getMethod();
    		// 连接点方法方法名
    		String name = method.getName();
    		Class<?>[] parameterTypes = method.getParameterTypes();
    		// 获取连接点所在的目标对象
    		Object target = jp.getTarget();
    		// 获取目标方法
    		method = target.getClass().getMethod(name, parameterTypes);
    		// 返回@AroundPointCut的注释对象
    		AroundPointCut joinPoint = method.getAnnotation(AroundPointCut.class);
    		if (!joinPoint.accessRead()) {
    			throw new ApplicationException("没有权限!");
    		}
    		return jp.proceed();
    	}
    }
    
  • 业务的服务添加@AroundPointCut注释
  • 如下:
    	@AroundPointCut(accessRead = true)
    	public Object queryProuct() throws ApplicationException {
    		//TODO
    		return null;
    	}
    

    [/list]