8

如果我@Validated向我的服务的接口/实现添加注释,那么该服务不再是事务性的。Stacktrace 显示没有TransactionInterceptor,但我只看到MethodValidationInterceptor. 如果我删除@Validated,那么我当然会看到TransactionInterceptorMethodValidationInterceptor消失。这些方面是否相互排斥?

@Service
//@Validated <- here is my problem :)
public interface AdminService {
  String test(String key, String result);
}

public class AdminServiceImpl implements AdminService, BeanNameAware, ApplicationContextAware {

  @Override
  @Transactional(transactionManager = "transactionManager")
  public String test(String key, String result) {

    return "hehe";
  }
}

@Configuration
@EnableAspectJAutoProxy(exposeProxy = true)
@EnableTransactionManagement(order = AspectPrecedence.TRANSACTION_MANAGEMENT_ORDER)
public class AppConfiguration {..}

在此处输入图像描述

在此处输入图像描述

4

1 回答 1

5

解决了

@Transactional并且当服务通过使用如下接口@Validated注入自己的代理时不要一起工作:ApplicationContextAware

  private String beanName;

  private AdminService self;

  @Override
  public void setBeanName(String beanName) {
    this.beanName = beanName;
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    self = applicationContext.getBean(beanName, AdminService.class);
  }

在调试过程中,我注意到在后处理阶段setApplicationContext()调用了该方法,其中( ) 和( and ) 也将原始 bean 包装到代理实例中。ApplicationContextAwareProcessorMethodValidationPostProcessor@ValidatedAnnotationAwareAspectJAutoProxyCreator@Transactional@Aspects

在此过程中间调用getBean()方法会导致 bean 未完全初始化,因为某些后处理操作未应用。在我的情况下TransactionInterceptor没有添加。

在此处输入图像描述

为了将自己的代理注入到服务中,我最终创建了专门的 Ordered BeaNPostProcessor 执行,LOWEST_PRECEDENCE以确保我在完全初始化的 bean 上进行操作。

于 2018-03-06T09:43:06.977 回答