Java 通过反射访问目标对象时未调用Spring AOP目标对象方面
我目前让SpringAOP在Springbean(目标实现)上定义一个日志方面(日志方面)。当我正常访问该方法(常规访问)时,我的实现运行并接收日志。但是,当我通过反射(反射访问)访问我的实现时,我的实现会运行,但不会收到任何日志记录。我想了解这是为什么,以及如何让基于反射的访问模式获取日志。参见参考图片 完整示例:(注意反射调用实际上来自父类) 父类(带反射调用) 日志方面Java 通过反射访问目标对象时未调用Spring AOP目标对象方面,java,spring,reflection,aspectj,spring-aop,Java,Spring,Reflection,Aspectj,Spring Aop,我目前让SpringAOP在Springbean(目标实现)上定义一个日志方面(日志方面)。当我正常访问该方法(常规访问)时,我的实现运行并接收日志。但是,当我通过反射(反射访问)访问我的实现时,我的实现会运行,但不会收到任何日志记录。我想了解这是为什么,以及如何让基于反射的访问模式获取日志。参见参考图片 完整示例:(注意反射调用实际上来自父类) 父类(带反射调用) 日志方面 @Aspect @Component public class MyEventValidatorLoggingAspe
@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");
}
}
如何调用
validateEvent()
?您可能在代理目标类上调用validateEvent
,而不是代理本身。我想你可能是对的。我如何调整它以访问代理本身?这就是为什么问你如何调用validateEvent()
。你可以用另一种方法:使用本机AspectJ(不是基于代理的)而不是Spring AOP(需要动态代理)来避免代理。如果不使用代理,则无论是直接调用还是通过反射调用方法,execution()。我可能会采用这种方法,但是,如何获得代理的引用?我通过直接从实现调用validateEvent来调用它
@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");
}
}