Wednesday, May 14, 2014

Setting transactional Spring components manually

There is an issue while setting @Transactional Spring components, because of proxies used to generate them. Here is an solution for that:

Setter:        
ReflectionTestUtils.setField( 
    TestUtils.unwrapTransactionalServiceSafe(serviceWithAutowiredComponents), 
    "externalService", newExternalServiceInstance );


Utils:
    public static Object unwrapTransactionalService( Object transactionalService ) throws Exception {
      if(AopUtils.isAopProxy(transactionalService) && transactionalService instanceof Advised) {
          Object target = ((Advised) transactionalService).getTargetSource().getTarget();
          return target;
      }
      return null;
    }
    public static Object unwrapTransactionalServiceSafe( Object transactionalService ){
        try {
            return unwrapTransactionalService( transactionalService );
        } catch (Exception ex) {
            throw new RuntimeException( ex );
        }
    }



No comments:

Post a Comment