[java][annotation][@Aspect]Java注解与切面使用

import org.springframework.kafka.annotation.KafkaListener;

import java.lang.annotation.*;


@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@KafkaListener
public @interface Listener {

    String[] topics() default {};

}

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class ListenAspect {
    @Before("@annotation(Listener)")
    public void beforeListener(JoinPoint point) {
        Object[] args = point.getArgs();
        if (args[0] != null && args[0] instanceof ConsumerRecord) {
            ConsumerRecord consumerRecord = (ConsumerRecord) args[0];
            log.debug("consumerRecord:{}", consumerRecord.toString());

            String value = consumerRecord.value().toString();
            log.trace("value:{}", value);
        }

        Class<?> className = point.getTarget().getClass();
        String methodName = point.getSignature().getName();
        Class[] argClass = ((MethodSignature) point.getSignature()).getParameterTypes();
        log.trace("className:" + className);
        log.trace("methodName:" + methodName);
        log.trace("argClass:" + argClass);

        if (argClass[0] != null) {
            log.trace("argClass[0]:" + argClass[0].toString());
//            try {
//                ConsumerRecord consumerRecord = (ConsumerRecord)argClass[0].newInstance();
//                log.debug("consumerRecord:{}", consumerRecord.toString());
//            } catch (InstantiationException|IllegalAccessException e) {
//                e.printStackTrace();
//            }
        }

        try {
            Method method = className.getMethod(methodName, argClass);
            log.trace("method:" + method);

            if (method.isAnnotationPresent(Listener.class)) {
                Listener annotation = method.getAnnotation(Listener.class);
                log.trace("annotation:" + annotation);
                log.trace("topics:" + annotation.topics());
            }
        } catch (Exception e) {
            log.warn(e.getMessage(), e);
        }
    }
}

转载于:https://my.oschina.net/u/2464371/blog/3056316

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值