【问题标题】:@Transactional does not work when @Validated@Validated 时 @Transactional 不起作用
【发布时间】:2018-08-10 21:38:41
【问题描述】:

如果我将@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 {..}

【问题讨论】:

  • 您要在服务层验证什么?在您的服务开始处理实体时,您在该级别收到的实体应该已经经过验证。
  • 你可能是对的,但这不是我问题的答案:(
  • 如果答案是“把你的验证放在那个级别没有意义,把它上移”,然后你就可以恢复你的交易......
  • 我刚刚检查了另一件事 @Validated 也关闭了其他方面为我的服务提供建议,因此可以肯定这种行为有问题:(
  • 来自文档;然而,类级别的注释对于触发特定 bean 的方法验证是必要的。也可以用作自定义原型注释或自定义组特定验证注释的元注释。

标签: spring validation transactions aop spring-aspects


【解决方案1】:

已解决

@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);
  }

在调试过程中,我注意到ApplicationContextAwareProcessor 在后期处理阶段调用了setApplicationContext() 方法,其中MethodValidationPostProcessor (@Validated) 和AnnotationAwareAspectJAutoProxyCreator (@Transactional@Aspects)将原始 bean 转换为代理实例。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-26
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多