通过反射

时间:2017-01-17 18:32:25

标签: java spring reflection aspectj spring-aop

我目前有Spring AOP定义了Spring Bean上的日志记录(Logging Aspect)方面(目标实现)。当我正常访问该方法时(常规访问)我的实施运行并且我收到日志。但是,当我通过反射(反射访问)访问我的实现我的实现运行,但我没有收到任何日志记录。我想了解为什么会这样,以及如何获得基于反射的访问模式来获取日志。见参考图片

Basic code flow

完整示例:(注意反射调用实际上来自父类)

父类(带反射调用)

public class EventValidationHandler {
    private List<Method> aggregateMethods;

    public EventValidationHandler() {
        aggregateMethods = getMethodsAnnotatedWithAggregateEventHandler(this.getClass());
    }

    public boolean validateEvent(DomainEvent event) throws Exception {
        Class clazz = event.getClass();
        for(Method method : aggregateMethods) {
            for(Class aClass : method.getParameterTypes()) {
                if(clazz.equals(aClass)) {
                    Object response = method.invoke(this, event);
                    return (Boolean) response;
                }
            }
        }
        throw new NoSuchMethodError("Unable to locate event validator method for event type: " + event.getClass().getSimpleName() + ".  Please confirm method is annotated with @" + EventValidator.class.getSimpleName());
    }

    private static List<Method> getMethodsAnnotatedWithAggregateEventHandler(final Class<?> type) {
        final List<Method> methods = new ArrayList<>();
        final List<Method> allMethods = new ArrayList<>(Arrays.asList(type.getDeclaredMethods()));
        for (final Method method : allMethods) {
            if (method.isAnnotationPresent(EventValidator.class)) {
                methods.add(method);
            }
        }
        return methods;
    }
}

实施

@Component
@AllArgsConstructor
public class MyEventValidator extends EventValidationHandler {
    private AggregateRepository aggregateRepository;

    @EventValidator
    public boolean isValid(CreateProfileEvent event) {
        if(aggregateRepository.findOne(event.getEmployeeId()) == null) {
            return true;
        }
        return false;
    }

    @EventValidator
    public boolean isValid(ChangePhoneNumberEvent event) {
        if(aggregateRepository.findOne(event.getEmployeeId()) != null) {
            return true;
        }
        return false;
    }
}

记录方面

@Aspect
@Component
public class MyEventValidatorLoggingAspect {
    public static Logger log = LoggerFactory.getLogger(MyEventValidator.class);

    @Pointcut("execution(* com.mcf7.eventsourcing.test.data.events.MyEventValidator.isValid(com.mcf7.eventsourcing.test.data.events.CreateProfileEvent))")
    private void createProfile() {}

    @Before("createProfile()")
    public void logHere(JoinPoint joinPoint) {
        log.info("super cool log of create profile");
    }
}

0 个答案:

没有答案