Java 类org.springframework.transaction.support.TransactionSynchronizationAdapter 实例源码

项目:IPPR2016    文件:ComposePersistenceActor.java   
private void handleComposeMessageCreateCommand(final Object obj) throws IOException {
  final ComposeMessageCreateCommand cmd = (ComposeMessageCreateCommand) obj;
  final Message message = new MessageBuilder().transferId(cmd.getTransferId())
      .messageState(MessageState.TO_COMPOSE).build();


  message.setInternalData(InternalDataUtils.convertInternalDataToJson(cmd.getData()));

  final BasicOutboundConfiguration configuration =
      basicConfigurationRepository.findOne(cmd.getConfigId());
  message.setOutboundConfiguration(configuration);

  messageRepository.save((MessageImpl) message);
  final String actorId = getContext().parent().path().name();
  TransactionSynchronizationManager
      .registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
          LOG.info("Saved new [{}]", message);
          getSender().tell(new ComposeMessageCreatedEvent(actorId, message.getId()), getSelf());
          stop();
        }
      });
}
项目:IPPR2016    文件:UserAssignmentsTask.java   
@Override
public void execute(final AssignUsersMessage.Request request) throws Exception {
  request.getUserAssignments().forEach(assignment -> {
    final Subject subject = subjectRepository
        .getSubjectForSubjectModelInProcess(request.getPiId(), assignment.getSmId());
    if (subject != null) {
      subject.setUser(assignment.getUserId());
      subjectRepository.save((SubjectImpl) subject);
      LOG.info("New user for subject: {}", subject);
    }
  });

  final ActorRef sender = getSender();
  TransactionSynchronizationManager
      .registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
          sender.tell(new AssignUsersMessage.Response(), getSelf());
        }
      });

}
项目:IPPR2016    文件:ComposePersistenceActor.java   
private void handleStoreExternalDataCommand(final Object obj) {
  final StoreExternalDataCommand cmd = (StoreExternalDataCommand) obj;
  final Message message = messageRepository.findOne(cmd.getId());
  message.setExternalData(cmd.getData());
  message.setMessageState(MessageState.COMPOSED);
  messageRepository.save((MessageImpl) message);
  final String actorId = getContext().parent().path().name();

  final ActorRef sender = getSender();
  TransactionSynchronizationManager
      .registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
          LOG.info("Updated external data of [{}]", message);
          sender.tell(new ComposedMessageEvent(actorId, message.getId()), getSelf());
          stop();
        }
      });
}
项目:spring-data-rest-webhook    文件:WebhookEntityListener.java   
@PostUpdate
@Async
public void postUpdate(Object object) {
    LOG.info("Listening to post update for object:" + object);
    // Entitys have to be annotated with @EventListeners and reference this class in that annotation, because of this
    // the usages of this class are not executed withing the handle of the Spring context. So now we have to use this funky
    // ass way of wiring in fields AS this method is being called. #sadface
    AutowireHelper.autowire(this);
    // Trying to just add @Transactional(Transactional.TxType.REQUIRES_NEW) to this method didn't work at all, it was just being ignored.
    // This wrapper is what ended up working.
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCompletion(int status) {
            super.afterCompletion(status);
            List<Webhook> hooks = webhookManager.retrieveWebhooksByEntityNameAndEventType(object.getClass().getSimpleName(), "post-update");
            hooks.stream().forEach(wh -> webhookProcessor.notifyWebhook(wh, object));
        }
    });

}
项目:oma-riista-web    文件:AllPartnersFinishedHuntingMailFeature.java   
private void sendMail(final HarvestPermit permit, final GameSpecies species) {
    final Set<String> emails = findEmails(permit);
    final AllPartnersFinishedHuntingMailService.MailData data = getMailData(permit, species);
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            try {
                // NOTE: Must invoke through proxy to make sure new transaction is started
                mailService.sendEmailAsync(emails, data);
            } catch (RuntimeException ex) {
                // Exception should be handled, so that HTTP status code is not altered
                LOG.error("Error occurred while sending emails", ex);
            }
        }
    });
}
项目:oma-riista-web    文件:LocalFolderFileStorage.java   
@Override
public void storeFile(final FileType fileType,
                      final PersistentFileMetadata metadata,
                      final InputStream inputStream) throws IOException {
    final Path storageFolder = fileType.resolveLocalStorageFolder(this.storageBasePath);
    final Path storageFile = storageFolder.resolve(fileType.formatFilename(metadata));

    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCompletion(final int status) {
            // Remove file if transaction is rolled back
            if (status == STATUS_ROLLED_BACK) {
                deleteIfExists(storageFile, false);
            }
        }
    });

    metadata.setResourceUrl(storageFile.toUri().toURL());

    try {
        Files.copy(inputStream, storageFile, StandardCopyOption.REPLACE_EXISTING);
    } finally {
        inputStream.close();
    }
}
项目:motech    文件:DefaultMotechDataService.java   
@Override
@Transactional
public T create(final T object) {
    validateCredentials();

    final T createdInstance = repository.create(object);

    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            if (allowCreateEvent) {
                sendEvent((Long) getId(createdInstance), CREATE);
            }
        }
    });

    return createdInstance;
}
项目:motech    文件:DefaultMotechDataService.java   
@Override
@Transactional
public T update(final T object) {
    if (JDOHelper.getObjectState(object) == ObjectState.TRANSIENT) {
        return updateFromTransient(object);
    } else {
        validateCredentials(object);

        updateModificationData(object);
        final T updatedInstance = repository.update(object);

        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                if (allowUpdateEvent) {
                    sendEvent((Long) getId(updatedInstance), UPDATE);
                }
            }
        });

        return updatedInstance;
    }
}
项目:runningdinner    文件:RunningDinnerServiceImpl.java   
@Transactional
public Team changeSingleTeamHost(final ChangeTeamHost changeTeamHost) {

    final String teamKey = changeTeamHost.getTeamKey();
    final String hostingParticipantKey = changeTeamHost.getHostingParticipantKey();

    final Team team = repository.loadSingleTeamWithVisitationPlan(teamKey, false);

    validateChangeTeamHost(changeTeamHost, team);

    changeSingleTeamHost(team, hostingParticipantKey);

    // Publish event only after transaction is successfully committed:
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            eventPublisher.notifyTeamHostChangeByParticipant(team, changeTeamHost);
        }
    });

    return team;
}
项目:gocd    文件:AgentDao.java   
public void associateCookie(final AgentIdentifier agentIdentifier, final String cookie) {
    final String uuid = agentIdentifier.getUuid();
    final String key = agentCacheKey(uuid);
    synchronized (key) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override protected void doInTransactionWithoutResult(TransactionStatus status) {
                Agent agent = fetchAgentByUuid(uuid);
                if (agent == null) {
                    agent = new Agent(uuid, cookie, agentIdentifier.getHostName(), agentIdentifier.getIpAddress());
                } else {
                    agent.update(cookie, agentIdentifier.getHostName(), agentIdentifier.getIpAddress());
                }
                getHibernateTemplate().saveOrUpdate(agent);
                synchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    @Override public void afterCommit() {
                        cache.remove(key);                            
                    }
                });
            }
        });
    }
}
项目:gocd    文件:PipelineSqlMapDao.java   
public Pipeline save(final Pipeline pipeline) {
    return (Pipeline) transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    goCache.remove(cacheKeyForLatestPipelineIdByPipelineName(pipeline.getName()));
                    invalidateCacheConditionallyForPipelineInstancesTriggeredWithDependencyMaterial(pipeline);
                }
            });

            Long pipelineId = (Long) getSqlMapClientTemplate().insert("insertPipeline", pipeline);
            savePipelineMaterialRevisions(pipeline, pipelineId);
            environmentVariableDao.save(pipelineId, EnvironmentVariableType.Trigger, pipeline.scheduleTimeVariables());
            return pipeline;
        }
    });
}
项目:gocd    文件:PipelineStateDao.java   
public void unlockPipeline(final String pipelineName) {
    synchronized (pipelineLockStateCacheKey(pipelineName)) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    @Override
                    public void afterCommit() {
                        clearLockedPipelineStateCache(pipelineName);
                    }
                });

                final String cacheKey = pipelineLockStateCacheKey(pipelineName);
                PipelineState fromCache = pipelineStateFor(pipelineName);
                PipelineState toBeSaved = null;
                if (fromCache == null) {
                    toBeSaved = new PipelineState(pipelineName);
                } else {
                    toBeSaved = (PipelineState) sessionFactory.getCurrentSession().load(PipelineState.class, fromCache.getId());
                }
                toBeSaved.unlock();
                sessionFactory.getCurrentSession().saveOrUpdate(toBeSaved);
            }
        });
    }
}
项目:gocd    文件:UserSqlMapDao.java   
private void changeEnabledStatus(final List<String> usernames, final boolean enabled) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    clearEnabledUserCountFromCache();
                }
            });
            String queryString = String.format("update %s set enabled = :enabled where name in (:userNames)", User.class.getName());
            Query query = sessionFactory.getCurrentSession().createQuery(queryString);
            query.setParameter("enabled", enabled);
            query.setParameterList("userNames", usernames);
            query.executeUpdate();
        }
    });
}
项目:gocd    文件:JobInstanceService.java   
private void notifyJobStatusChangeListeners(final JobInstance job) {
    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            List<JobStatusListener> listeners1;
            synchronized (LISTENERS_MODIFICATION_MUTEX) {
                listeners1 = new ArrayList<>(listeners);
            }
            for (JobStatusListener jobStatusListener : listeners1)
                try {
                    jobStatusListener.jobStatusChanged(job);
                } catch (Exception e) {
                    LOGGER.error("error notifying listener for job {}", job, e);
                }
        }
    });
}
项目:gocd    文件:TransactionTemplateTest.java   
@Test
public void shouldAllowRegistrationOfTransactionSynchronization_inTransactionSurroundingBlock_andNotExecuteSynchronizationIfTransactionNeverHappens() {
    TransactionTemplate template = new TransactionTemplate(transactionTemplate);

    final boolean[] afterCommitHappened = new boolean[1];

    String returnVal = (String) template.transactionSurrounding(new TransactionTemplate.TransactionSurrounding<RuntimeException>() {
        public Object surrounding() {
            transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override public void afterCommit() {
                    afterCommitHappened[0] = true;
                }
            });
            return "bar";
        }
    });

    assertThat(returnVal, is("bar"));
    assertThat(afterCommitHappened[0], is(false));
}
项目:gocd    文件:TransactionTemplateTest.java   
@Test
public void shouldPropagateExceptionsOutOfTransactionSurrounding() throws IOException {
    TransactionTemplate template = new TransactionTemplate(transactionTemplate);

    final boolean[] afterCommitHappened = new boolean[1];

    String returnVal = null;
    try {
        returnVal = (String) template.transactionSurrounding(new TransactionTemplate.TransactionSurrounding<IOException>() {
            public Object surrounding() throws IOException {
                transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    @Override public void afterCommit() {
                        afterCommitHappened[0] = true;
                    }
                });
                throw new IOException("boo ha!");
            }
        });
        fail("should have propagated exception");
    } catch (IOException e) {
        assertThat(e.getMessage(), is("boo ha!"));
    }

    assertThat(returnVal, nullValue());
    assertThat(afterCommitHappened[0], is(false));
}
项目:code-examples-and-poc    文件:BlogEventListener.java   
@EventListener
public void blogAddedTransactionalOldSchool(final BlogAddedEvent blogAddedEvent) {
    //Note: *Old school* transaction handling before Spring 4.2
    if (TransactionSynchronizationManager.isActualTransactionActive()) {    //To not fail with "java.lang.IllegalStateException: Transaction synchronization is not active"
        TransactionSynchronizationManager.registerSynchronization(
                new TransactionSynchronizationAdapter() {
                    @Override
                    public void afterCommit() {
                        internalSendBlogAddedNotification(blogAddedEvent);
                    }
                });
    } else {
        log.warn("No active transaction found. Sending notification immediately.");
        internalSendBlogAddedNotification(blogAddedEvent);
    }
}
项目:IPPR2016    文件:StateObjectChangeTask.java   
private void handleStateObjectChangeMessage(final StateObjectChangeMessage.Request request)
    throws Exception {
  final SubjectState subjectState = Optional
      .ofNullable(
          subjectStateRepository.getSubjectStateOfUser(request.getPiId(), request.getUserId()))
      .get();

  sender = getSender();

  final ActorRef bussinessObjectCheckActor = getContext().actorOf(
      springExtension.props("BusinessObjectCheckActor", subjectState.getCurrentState().getSId()),
      UUID.randomUUID().toString());

  // must block thread since transaction is lost when using completable future
  final Future<Object> future = Patterns.ask(bussinessObjectCheckActor, request, Global.TIMEOUT);
  final boolean correct =
      ((Boolean) Await.result(future, Global.TIMEOUT.duration())).booleanValue();

  if (!correct) {
    sender.tell(new Status.Failure(
        new IllegalArgumentException("Check of business objects returned false")), getSelf());
  } else {
    initBusinessObjectInstances(subjectState, request);
    setValuesOfBusinessObjectFieldInstances(subjectState.getCurrentState(), request);
    sendMessages(subjectState, request);

    TransactionSynchronizationManager
        .registerSynchronization(new TransactionSynchronizationAdapter() {
          @Override
          public void afterCommit() {
            sender.tell(new EmptyMessage(), getSelf());
            handleAdditionalActions(subjectState);
          }
        });
  }
}
项目:IPPR2016    文件:SendMessagesTask.java   
@Override
public void execute(final MessagesSendMessage.Request request) throws Exception {
  final List<CompletableFuture<Object>> futures =
      request.getUserMessageFlowIds()
          .stream().map(userMessageFlow -> convertToFuture(request.getPiId(),
              userMessageFlow.getLeft(), userMessageFlow.getRight()))
          .collect(Collectors.toList());

  final ActorRef sender = getSender();

  try {
    CompletableFuture.allOf(Iterables.toArray(futures, CompletableFuture.class)).get();
    LOG.info("All users received the message in PI_ID [{}]", request.getPiId());
    final SubjectState sendState = subjectStateRepository.findOne(request.getSendSubjectState());
    sendState.setToSent();
    subjectStateRepository.save((SubjectStateImpl) sendState);
    LOG.debug("{} is set to 'SENT'", sendState);
  } catch (final Exception e) {
    LOG.error("At least one user did not receive the message in PI_ID [{}]", request.getPiId());
    sender.tell(
        new Status.Failure(new IllegalStateException(
            "Could not send message to all users in PI_ID [" + request.getPiId() + "]")),
        getSelf());
  }

  TransactionSynchronizationManager
      .registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
          sender.tell(new MessagesSendMessage.Response(), getSelf());
        }
      });
}
项目:IPPR2016    文件:ProcessStopTask.java   
@Override
public void execute(final ProcessStopMessage.Request msg) throws Exception {
  final Optional<ProcessInstance> processOpt =
      Optional.ofNullable(processInstanceRepository.findOne(msg.getPiId()));
  if (!processOpt.isPresent()) {
    throw new IllegalArgumentException();
  }

  final ProcessInstance process = processOpt.get();
  if (!process.getState().equals(ProcessInstanceState.ACTIVE)) {
    throw new IllegalStateException();
  }

  process.setState(ProcessInstanceState.CANCELLED_BY_USER);

  TransactionSynchronizationManager
      .registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
          LOG.info("Process was stopped: {}", process);
          final ProcessInfoDTO dto = new ProcessInfoDTO(process.getPiId(), process.getStartTime(),
              process.getEndTime(), process.getProcessModel().getName(), process.getStartUserId(),
              process.getState().name());
          getSender().tell(new ProcessStopMessage.Response(dto), getSelf());
          callback();
        }
      });
}
项目:Equella    文件:AbstractBaseEntityEditor.java   
protected void publishEventAfterCommit(final ApplicationEvent<?> event)
{
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter()
    {
        @Override
        public void afterCommit()
        {
            eventService.publishApplicationEvent(event);
        }
    });
}
项目:Equella    文件:AbstractEntityServiceImpl.java   
protected void publishEventAfterCommit(final ApplicationEvent<?> event)
{
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter()
    {
        @Override
        public void afterCommit()
        {
            eventService.publishApplicationEvent(event);
        }
    });
}
项目:Equella    文件:ItemStandardServiceImpl.java   
private void publishEventAfterCommit(final ApplicationEvent<?> event)
{
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter()
    {
        @Override
        public void afterCommit()
        {
            eventService.publishApplicationEvent(event);
        }
    });
}
项目:Equella    文件:ItemServiceImpl.java   
protected void perItemPostProcess(final ItemOperationParams params)
{
    final List<ApplicationEvent<?>> eventList = new ArrayList<ApplicationEvent<?>>(params.getAfterCommitEvents());
    final List<Runnable> afterCommitHooks = new ArrayList<Runnable>(params.getAfterCommit());
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter()
    {
        @Override
        public void afterCommit()
        {
            afterCommitOne(eventList, afterCommitHooks);
        }
    });
}
项目:Equella    文件:ItemServiceImpl.java   
private void postProcessParameters(final ItemOperationParams params)
{
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter()
    {
        @Override
        public void afterCommit()
        {
            afterCommitAll(params);
        }
    });
}
项目:Equella    文件:WorkflowStandardServiceImpl.java   
private void publishEventAfterCommit(final ApplicationEvent<?> event)
{
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter()
    {
        @Override
        public void afterCommit()
        {
            eventService.publishApplicationEvent(event);
        }
    });
}
项目:lams    文件:TransactionAwareCacheDecorator.java   
@Override
public void put(final Object key, final Object value) {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                targetCache.put(key, value);
            }
        });
    }
    else {
        this.targetCache.put(key, value);
    }
}
项目:lams    文件:TransactionAwareCacheDecorator.java   
@Override
public void evict(final Object key) {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                targetCache.evict(key);
            }
        });
    }
    else {
        this.targetCache.evict(key);
    }
}
项目:lams    文件:TransactionAwareSessionContext.java   
/**
    * Creates a transaction synchronization object for the specified session.
    *
    * @param session
    *            Session to synchronize using the created object. Cannot be null.
    * @return A valid transaction synchronization. Never returns null.
    */
   private TransactionSynchronization createTransactionSynchronization(final Session session) {
return new TransactionSynchronizationAdapter() {
    @Override
    public void afterCompletion(final int status) {
    session.close();
    ManagedSessionContext.unbind(sessionFactory);
    }
};
   }
项目:spring-seed    文件:ExpirableTransactionAwareCacheDecorator.java   
@Override
public void put(final Object key, final Object value, final long expiration) {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                targetCache.put(key, value, expiration);
            }
        });
    }
    else {
        this.targetCache.put(key, value, expiration);
    }
}
项目:oma-riista-web    文件:RegisterHuntingClubFeature.java   
private void sendNotificationEmail(final HuntingClub club,
                                   final SystemUser activeUser,
                                   final Occupation contactPerson,
                                   final Organisation rhy) {
    // Send notification email after transaction has committed successfully
    final HuntingClubDTO clubDTO = HuntingClubDTO.create(club, false, null, null);
    final OccupationDTO occupationDTO = OccupationDTO.createWithPerson(contactPerson);
    final OrganisationNameDTO rhyDTO = OrganisationNameDTO.create(rhy);

    final String contactPersonEmail = activeUser.getEmail();
    final Iterable<String> rhyContactEmails = registerHuntingClubMailService.getRhyContactEmails(rhy);

    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            try {
                // NOTE: Must invoke through proxy to make sure new transaction is started
                registerHuntingClubMailService.sendNotificationEmail(
                        clubDTO, occupationDTO, rhyDTO, rhyContactEmails, contactPersonEmail);

            } catch (RuntimeException ex) {
                // Exception should be handled, so that HTTP status code is not altered
                LOG.error("Error occured while sending notification emails", ex);
            }
        }
    });
}
项目:oma-riista-web    文件:AuditService.java   
private static void doLogAfterTransaction(final String msg) {
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            doLog(msg);
        }
    });
}
项目:oma-riista-web    文件:LocalFolderFileStorage.java   
@Override
public void removeFromStorage(PersistentFileMetadata metadata) {
    final Path storageFile = getFileStoragePath(metadata);

    // Delay until transaction has completed with success.
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            deleteIfExists(storageFile, true);
        }
    });
}
项目:oma-riista-web    文件:S3FileStorage.java   
@Override
public void removeFromStorage(final PersistentFileMetadata metadata) {
    // Invoked before session closed
    final S3Util.BucketObjectPair s3Object = S3Util.parseResourceURL(metadata.getResourceUrl());

    // Delay S3 object delete until transaction is complete and successful
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            removeInternal(s3Object);
        }
    });
}
项目:spring4-understanding    文件:TransactionAwareCacheDecorator.java   
@Override
public void put(final Object key, final Object value) {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                targetCache.put(key, value);
            }
        });
    }
    else {
        this.targetCache.put(key, value);
    }
}
项目:spring4-understanding    文件:TransactionAwareCacheDecorator.java   
@Override
public void evict(final Object key) {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                targetCache.evict(key);
            }
        });
    }
    else {
        this.targetCache.evict(key);
    }
}
项目:spring4-understanding    文件:TransactionAwareCacheDecorator.java   
@Override
public void clear() {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                targetCache.clear();
            }
        });
    }
    else {
        this.targetCache.clear();
    }
}
项目:metaworks_framework    文件:CustomerPersistedEntityListener.java   
/**
 * Invoked on both the PostPersist and PostUpdate. The default implementation is to simply publish a Spring event
 * to the ApplicationContext after the transaction has completed.
 * 
 * @param entity the newly-persisted Customer
 * @see CustomerPersistedEvent
 */
@PostPersist
@PostUpdate
public void customerUpdated(final Object entity) {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                ApplicationContextHolder.getApplicationContext().publishEvent(new CustomerPersistedEvent((Customer) entity));
            }
        });
    }
}
项目:metaworks_framework    文件:OrderPersistedEntityListener.java   
/**
 * Invoked on both the PostPersist and PostUpdate. The default implementation is to simply publish a Spring event
 * to the ApplicationContext to allow an event listener to respond appropriately (like resetting the current cart
 * in CartState)
 * 
 * @param entity the newly-persisted Order
 * @see OrderPersistedEvent
 */
@PostPersist
@PostUpdate
public void customerUpdated(final Object entity) {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                ApplicationContextHolder.getApplicationContext().publishEvent(new OrderPersistedEvent((Order) entity));
            }
        });
    }
}
项目:opencucina    文件:TransactionHandlerImpl.java   
/**
 *
 *
 * @see org.cucina.engine.client.service.TransactionHandler#registerTxHandler
 * (java.lang.String, java.io.Serializable)
 */
@Override
public void registerTxHandler(final String entityType, final Serializable... ids) {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCompletion(int status) {
                    handleStatus(status, entityType, ids);
                }
            });
    }
}