spring 基于Aspect和注解的切面编程(aop)

spring bean配置中

<bean id="toggleDataSourceAdvice" class="com.gsww.jzfp.core.dataresource.aop.ToggleDataSourceAdvice">
	</bean>
    <aop:aspectj-autoproxy/>

注解代码如下:

/**
 * 用于注解数据切换
 * @author wyy
 *@version 2015-12-02
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ToggleDataSource {

	/**
	 * 数据源名称
	 * @return
	 */
	String name() default DataSourceContextHolder.BASE;
}

切面通知基类

/**
 * 切面通知抽象基类
 * @author wyy
 *@version 2015-12-02
 * @param <T>
 */
public abstract class AbstractAdvice<T extends Annotation> {
	protected final Class<T> annotationClass;

	protected AbstractAdvice(final Class<T> annotationClass) {
		this.annotationClass = annotationClass;
	}
	
	protected abstract Logger getLogger();
	
	protected void warn(final Exception e, final String format, final Object... args) {
        if (getLogger().isWarnEnabled()) {
            getLogger().warn(String.format(format, args), e);
        }
    }
	
	protected Method getMethod(final JoinPoint jp)
			throws NoSuchMethodException {
		final Signature sig = jp.getSignature();
		if (!(sig instanceof MethodSignature)) {
			throw new InvalidAnnotationException(
					"This annotation is only valid on a method.");
		}

		final MethodSignature msig = (MethodSignature) sig;
		final Object target = jp.getTarget();

		// cannot use msig.getMethod() because it can return the method where
		// annotation was declared i.e. method in
		// interface
		String name = msig.getName();
		Class<?>[] parameters = msig.getParameterTypes();

		Method method = findMethodFromTargetGivenNameAndParams(target, name,
				parameters);

		return method;
	}
	
	protected Method findMethodFromTargetGivenNameAndParams(
			final Object target, final String name, final Class<?>[] parameters)
			throws NoSuchMethodException {
		Method method = target.getClass().getMethod(name, parameters);
		getLogger().debug("Method to cache: {}", method);

		return method;
	}
	
	protected void verifyReturnTypeIsList(final Method method, final Class<?> annotationClass) {
        if (!verifyTypeIsList(method.getReturnType())) {
            throw new InvalidAnnotationException(
                    String.format("The annotation [%s] is only valid on a method that returns a [%s] or its subclass. "
                            + "[%s] does not fulfill this requirement.", annotationClass.getName(), List.class.getName(), method.toString()));
        }
    }
	protected boolean verifyTypeIsList(final Class<?> clazz) {
        return List.class.isAssignableFrom(clazz);
    }

    protected void verifyReturnTypeIsNoVoid(final Method method, final Class<?> annotationClass) {
        if (method.getReturnType().equals(void.class)) {
            throw new InvalidParameterException(String.format("Annotation [%s] is defined on void method  [%s]", annotationClass,
                    method.getName()));
        }
    }
}


切面处理类

/**
 * 
 * <bean id="toggleDataSourceAdvice" class="com.gsww.jzfp.core.dataresource.aop.ToggleDataSourceAdvice"></bean>
 *  <aop:aspectj-autoproxy/> 
 * 
 */

/**
 * 
 * @author QQ:16349023
 *
 */
@Aspect
public class ToggleDataSourceAdvice extends AbstractAdvice<ToggleDataSource> {
	private static final Logger LOG = LoggerFactory.getLogger(ToggleDataSourceAdvice.class);
	
	public ToggleDataSourceAdvice(){
		super(ToggleDataSource.class);
	}
	
	@Pointcut("@annotation(com.gsww.jzfp.core.dataresource.aop.ToggleDataSource)")
    public void getTargetMethod() {
        /* pointcut definition */
    }

    @Around("getTargetMethod()")
    public Object around(final ProceedingJoinPoint pjp) throws Throwable {
        //return cache(pjp);
    	//System.out.println("Around1***********************");
    	
    	final ToggleDataSource annotation;
    	Object result;
    	try {
            final Method method = getMethod(pjp);
            System.out.println("method:"+method.toString());
            
            annotation = method.getAnnotation(ToggleDataSource.class);
            //根据注解在方法执行前进行处理 to do
            System.out.println("annotation:"+annotation.toString());
            result = pjp.proceed();
        } catch (Exception ex) {
            warn(ex, "Caching on method %s and key [%s] aborted due to an error.", pjp.toShortString());
            result = pjp.proceed();
        }
    	//final Object result = pjp.proceed();
    	//System.out.println("Around2***********************");
    	
    	return result;
    }
    
    @Before("getTargetMethod()")
    public void before() throws Throwable{
    	
    	System.out.println("before***********************");
    }
    
    @After("getTargetMethod()")
    public void after() throws Throwable{
    	System.out.println("after**************************");
    }
	
    
    @Override
	protected Logger getLogger() {
        return LOG;
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值