Spring AOP处理类上或者方法上面的切面

Posted javartisan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring AOP处理类上或者方法上面的切面相关的知识,希望对你有一定的参考价值。

 

注解定义

@Target(ElementType.METHOD, ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XXXXDataSource 

    /**
     * @return datasource name
     */
    DataSourceType value();

数据源名字

public enum DataSourceType 

    NEO("NEO"),
    // data_mill 原始的线上数据库
    mysql("MYSQL"),
    AUDIENCE("AUDIENCE"),
    REACH("REACH"),
    INSIGHT("INSIGHT"),
    ACTIVITY("ACTIVITY");

    public final String type;

    DataSourceType(String type) 
        this.type = type;
    

    public static final Set<DataSourceType> dataSourceTypeSet = new HashSet<>();

    static 
        for (DataSourceType type : DataSourceType.values()) 
            dataSourceTypeSet.add(type);
        
    

 

处理多数据源切面


@Aspect
@Component
public class DataSourceAspect 

    public static Logger LOGGER = LoggerFactory.getLogger(DataSourceAspect.class);

    /**
     * 处理类上面的注解
     *
     * @param pjp
     * @param value
     * @return
     * @throws Throwable
     */
    @Around(value = "@within(value)")
    public Object processMethod(ProceedingJoinPoint pjp, XXXDataSource value) throws Throwable 
        return process(pjp, value);
    

    /**
     * 处理方法上面的注解
     *
     * @param pjp
     * @param value
     * @return
     * @throws Throwable
     */
    @Around(value = "@annotation(value)")
    public Object processClass(ProceedingJoinPoint pjp, XXXDataSource value) throws Throwable 
        return process(pjp, value);
    

    public Object process(ProceedingJoinPoint pjp, XXXDataSource value) throws Throwable 

        if (!check(value)) 
            throw new RuntimeException("DataSource can't be understand, dataSource info = " + value);
        

        String args = Arrays.toString(pjp.getArgs());
        Signature methodName = pjp.getSignature();
        LOGGER.info("methodName =  datasource =  and args =  start proceed !", methodName.getName(), value.value().type, args);
        MDC.put(DATASOURCE_TYPE_KEY, value.value().type);
        Object returnValue = pjp.proceed();
        LOGGER.info("methodName =  and args =   and returnValue = proceed finished !", methodName.getName(), args, returnValue);
        MDC.remove(value.value().type);
        return returnValue;
    

    public boolean check(XXXDataSource value) 
        return value != null && DataSourceType.dataSourceTypeSet.contains(value.value());
    

 

以上是关于Spring AOP处理类上或者方法上面的切面的主要内容,如果未能解决你的问题,请参考以下文章

AOP进行通知(切面)的步骤

Spring AOP(面向切面编程)

Spring注解驱动开发-AOPTx和Servlet3.0

springBoot AOP学习

Srping全注解开发---AOP模块

spring源码学习-springAOP的使用和源码