@Test public void serializable() throws Exception { TestBean1 tb = new TestBean1(); CallCountingTransactionManager ptm = new CallCountingTransactionManager(); AnnotationTransactionAttributeSource tas = new AnnotationTransactionAttributeSource(); TransactionInterceptor ti = new TransactionInterceptor(ptm, tas); ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setInterfaces(new Class[] {ITestBean.class}); proxyFactory.addAdvice(ti); proxyFactory.setTarget(tb); ITestBean proxy = (ITestBean) proxyFactory.getProxy(); proxy.getAge(); assertEquals(1, ptm.commits); ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy); serializedProxy.getAge(); Advised advised = (Advised) serializedProxy; TransactionInterceptor serializedTi = (TransactionInterceptor) advised.getAdvisors()[0].getAdvice(); CallCountingTransactionManager serializedPtm = (CallCountingTransactionManager) serializedTi.getTransactionManager(); assertEquals(2, serializedPtm.commits); }
@Override public void before(Method method, Object[] args, Object target) throws Throwable { // do transaction checks if (requireTransactionContext) { TransactionInterceptor.currentTransactionStatus(); } else { try { TransactionInterceptor.currentTransactionStatus(); throw new RuntimeException("Shouldn't have a transaction"); } catch (NoTransactionException ex) { // this is Ok } } super.before(method, args, target); }
private DefaultTokenServices txProxiedTokenServices(DefaultTokenServices tokenServices, DataSource dataSource) { AnnotationTransactionAttributeSource attrSource = new AnnotationTransactionAttributeSource(); DataSourceTransactionManager txManager = new DataSourceTransactionManager(dataSource); TransactionInterceptor txInterceptor = transactionInterceptor(attrSource, txManager); BeanFactoryTransactionAttributeSourceAdvisor txAdvisor = transactionAdvisor(attrSource, txInterceptor); ClassLoader classLoader = ClassUtils.getDefaultClassLoader(); ProxyFactory proxyFactory = new ProxyFactory(tokenServices); proxyFactory.addAdvice(txInterceptor); proxyFactory.addAdvisor(txAdvisor); proxyFactory.setInterfaces( ClassUtils.getAllInterfacesForClass( new SingletonTargetSource(tokenServices).getTargetClass(), classLoader)); return (DefaultTokenServices) proxyFactory.getProxy(classLoader); }
@Test public void testSerializable() throws Exception { TestBean1 tb = new TestBean1(); CallCountingTransactionManager ptm = new CallCountingTransactionManager(); AnnotationTransactionAttributeSource tas = new AnnotationTransactionAttributeSource(); TransactionInterceptor ti = new TransactionInterceptor(ptm, tas); ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setInterfaces(new Class[] {ITestBean.class}); proxyFactory.addAdvice(ti); proxyFactory.setTarget(tb); ITestBean proxy = (ITestBean) proxyFactory.getProxy(); proxy.getAge(); assertEquals(1, ptm.commits); ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy); serializedProxy.getAge(); Advised advised = (Advised) serializedProxy; TransactionInterceptor serializedTi = (TransactionInterceptor) advised.getAdvisors()[0].getAdvice(); CallCountingTransactionManager serializedPtm = (CallCountingTransactionManager) serializedTi.getTransactionManager(); assertEquals(2, serializedPtm.commits); }
/** * 定义事务切入点,方法名称就是Bean名称 */ @Bean public TransactionInterceptor transactionInterceptor(PlatformTransactionManager manager) { Properties props = new Properties(); props.setProperty("save*", "PROPAGATION_REQUIRED,-java.lang.RuntimeException"); props.setProperty("update*", "PROPAGATION_REQUIRED,-java.lang.RuntimeException"); props.setProperty("remove*", "PROPAGATION_REQUIRED,-java.lang.RuntimeException"); props.setProperty("*", "PROPAGATION_NOT_SUPPORTED,readOnly"); return new TransactionInterceptor(manager, props); }
/** * 织入 */ @Bean public DefaultPointcutAdvisor defaultPointcutAdvisor(TransactionInterceptor interceptor) { // 切入点 AspectJExpressionPointcut expression = new AspectJExpressionPointcut(); expression.setExpression("execution(* org.sj.alexa.service.tx.I*Service.*(..))"); return new DefaultPointcutAdvisor(expression, interceptor); }
@Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public TransactionInterceptor transactionInterceptor() { TransactionInterceptor interceptor = new TransactionInterceptor(); interceptor.setTransactionAttributeSource(transactionAttributeSource()); if (this.txManager != null) { interceptor.setTransactionManager(this.txManager); } return interceptor; }
public static void configureAutoProxyCreator(Element element, ParserContext parserContext) { AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element); String txAdvisorBeanName = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME; if (!parserContext.getRegistry().containsBeanDefinition(txAdvisorBeanName)) { Object eleSource = parserContext.extractSource(element); // Create the TransactionAttributeSource definition. RootBeanDefinition sourceDef = new RootBeanDefinition( "org.springframework.transaction.annotation.AnnotationTransactionAttributeSource"); sourceDef.setSource(eleSource); sourceDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); String sourceName = parserContext.getReaderContext().registerWithGeneratedName(sourceDef); // Create the TransactionInterceptor definition. RootBeanDefinition interceptorDef = new RootBeanDefinition(TransactionInterceptor.class); interceptorDef.setSource(eleSource); interceptorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registerTransactionManager(element, interceptorDef); interceptorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName)); String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef); // Create the TransactionAttributeSourceAdvisor definition. RootBeanDefinition advisorDef = new RootBeanDefinition(BeanFactoryTransactionAttributeSourceAdvisor.class); advisorDef.setSource(eleSource); advisorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); advisorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName)); advisorDef.getPropertyValues().add("adviceBeanName", interceptorName); if (element.hasAttribute("order")) { advisorDef.getPropertyValues().add("order", element.getAttribute("order")); } parserContext.getRegistry().registerBeanDefinition(txAdvisorBeanName, advisorDef); CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), eleSource); compositeDef.addNestedComponent(new BeanComponentDefinition(sourceDef, sourceName)); compositeDef.addNestedComponent(new BeanComponentDefinition(interceptorDef, interceptorName)); compositeDef.addNestedComponent(new BeanComponentDefinition(advisorDef, txAdvisorBeanName)); parserContext.registerComponent(compositeDef); } }
@Bean public TransactionInterceptor transactionInterceptor(PlatformTransactionManager transactionManager) { Properties attributes = new Properties(); attributes.setProperty("get*", "PROPAGATION_REQUIRED"); attributes.setProperty("put*", "PROPAGATION_REQUIRED"); attributes.setProperty("post*", "PROPAGATION_REQUIRED"); attributes.setProperty("delete*", "PROPAGATION_REQUIRED"); return new TransactionInterceptor(transactionManager, attributes); }
@Bean(name="txAdvice") public TransactionInterceptor getAdvisor() throws Exception{ Properties properties = new Properties(); properties.setProperty("*", "PROPAGATION_REQUIRED,-Exception"); TransactionInterceptor tsi = new TransactionInterceptor(transactionManager,properties); return tsi; }
/** * 读取事务管理中的策略 * * @param txAdvice * @throws Exception */ @SuppressWarnings("unchecked") public void setTxAdvice(TransactionInterceptor txAdvice) throws Exception { if (txAdvice == null) { // 没有配置事务管理策略 return; } // 从txAdvice获取到策略配置信息 TransactionAttributeSource transactionAttributeSource = txAdvice.getTransactionAttributeSource(); if (!(transactionAttributeSource instanceof NameMatchTransactionAttributeSource)) { return; } // 使用反射技术获取到NameMatchTransactionAttributeSource对象中的nameMap属性值 NameMatchTransactionAttributeSource matchTransactionAttributeSource = (NameMatchTransactionAttributeSource) transactionAttributeSource; Field nameMapField = ReflectionUtils.findField(NameMatchTransactionAttributeSource.class, "nameMap"); nameMapField.setAccessible(true); // 设置该字段可访问 // 获取nameMap的值 Map<String, TransactionAttribute> map = (Map<String, TransactionAttribute>) nameMapField.get(matchTransactionAttributeSource); // 遍历nameMap for (Map.Entry<String, TransactionAttribute> entry : map.entrySet()) { if (!entry.getValue().isReadOnly()) {// 判断之后定义了ReadOnly的策略才加入到slaveMethodPattern continue; } slaveMethodPattern.add(entry.getKey()); } }
@Test public void rollbackRules() { TransactionInterceptor txInterceptor = (TransactionInterceptor) context.getBean("txRollbackAdvice"); TransactionAttributeSource txAttrSource = txInterceptor.getTransactionAttributeSource(); TransactionAttribute txAttr = txAttrSource.getTransactionAttribute(getAgeMethod,ITestBean.class); assertTrue("should be configured to rollback on Exception",txAttr.rollbackOn(new Exception())); txAttr = txAttrSource.getTransactionAttribute(setAgeMethod, ITestBean.class); assertFalse("should not rollback on RuntimeException",txAttr.rollbackOn(new RuntimeException())); }
/** * Evaluate the result of the note creation operation and send appropriate feedback messages. * * @param result * the note creation result * @param sender * the user that sent the processed enauk * @param blogId * the ID of the target blog * @param creatorId * Id of the messages author. */ private void evaluateNoteModificationResult(NoteModificationResult result, User sender, Long blogId, Long creatorId) { String alias = userManagement.findUserByUserId(creatorId).getAlias(); result.getUserNotificationResult().getUnresolvableUsers().remove(alias); result.getUserNotificationResult().getUninformableUsers().remove(alias); if (result.getStatus().equals(NoteModificationStatus.SUCCESS)) { if (result.getUserNotificationResult().getUnresolvableUsers().size() != 0 || result.getUserNotificationResult().getUninformableUsers().size() != 0 || result.getUnresolvableBlogs().size() != 0 || result.getUnwritableBlogs().size() != 0) { sendErrorMailMessage(new WarningMailMessage(sender, result .getUserNotificationResult().getUnresolvableUsers(), result .getUserNotificationResult().getUninformableUsers(), result.getUnresolvableBlogs(), result.getUnwritableBlogs(), getBlogTitle(blogId), result.isDirect())); } } else { if (TransactionInterceptor.currentTransactionStatus().isRollbackOnly()) { // explicitly mark this transaction as rollback-only because inner transaction // is marked too TransactionInterceptor.currentTransactionStatus().setRollbackOnly(); } String errorMessage = CreateBlogPostHelper.getFeedbackMessageAfterModification(result, sender.getLanguageLocale()); sendErrorMailMessage(new GenericErrorMailMessage(sender, errorMessage, getBlogTitle(blogId))); } }
@Override protected void configure() { // TransactionManager PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); // TransactionInterceptor TransactionInterceptor transactionInterceptor = new TransactionInterceptor(transactionManager, new AnnotationTransactionAttributeSource(false)); bindInterceptor(Matchers.any(), Matchers.annotatedWith(Transactional.class), transactionInterceptor); bind(PlatformTransactionManager.class).toInstance(transactionManager); }
@Test public void testAutoConfigureComponents() { // @AutoConfigureMybatis this.applicationContext.getBean(JdbcTemplate.class); this.applicationContext.getBean(NamedParameterJdbcTemplate.class); this.applicationContext.getBean(DataSourceTransactionManager.class); this.applicationContext.getBean(TransactionInterceptor.class); // @AutoConfigureCache this.applicationContext.getBean(CacheManager.class); this.applicationContext.getBean(CacheInterceptor.class); }
/** * Construit un transactionInterceptor avec une configuration par défaut. */ public static TransactionInterceptor defaultTransactionInterceptor(PlatformTransactionManager transactionManager, List<Class<? extends Exception>> additionalRollbackRuleExceptions) { TransactionInterceptor transactionInterceptor = new TransactionInterceptor(); Properties transactionAttributes = new Properties(); List<RollbackRuleAttribute> rollbackRules = Lists.newArrayList(); rollbackRules.add(new RollbackRuleAttribute(ServiceException.class)); // TODO voir si on ajoute SecurityServiceException.class en fonction de ce que ça donne sur le Wombat // ou voir si on ne la dégage pas carrément en fait... for (Class<? extends Exception> clazz : additionalRollbackRuleExceptions) { rollbackRules.add(new RollbackRuleAttribute(clazz)); } DefaultTransactionAttribute readOnlyTransactionAttributes = new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED); readOnlyTransactionAttributes.setReadOnly(true); RuleBasedTransactionAttribute writeTransactionAttributes = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, rollbackRules); String readOnlyTransactionAttributesDefinition = readOnlyTransactionAttributes.toString(); String writeTransactionAttributesDefinition = writeTransactionAttributes.toString(); // read-only transactionAttributes.setProperty("is*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("has*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("get*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("list*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("search*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("find*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("count*", readOnlyTransactionAttributesDefinition); // write et rollback-rule transactionAttributes.setProperty("*", writeTransactionAttributesDefinition); transactionInterceptor.setTransactionAttributes(transactionAttributes); transactionInterceptor.setTransactionManager(transactionManager); return transactionInterceptor; }
@Override public void postProcessBeanFactory(final ConfigurableListableBeanFactory factory) throws BeansException { String[] names = factory.getBeanNamesForType(TransactionInterceptor.class); for (String name : names) { BeanDefinition bd = factory.getBeanDefinition(name); bd.setBeanClassName(DynamicTransactionInterceptor.class.getName()); } }
private BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor( AnnotationTransactionAttributeSource source, TransactionInterceptor interceptor) { BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor(); advisor.setTransactionAttributeSource(source); advisor.setAdvice(interceptor); return advisor; }
private TransactionInterceptor transactionInterceptor( AnnotationTransactionAttributeSource source, PlatformTransactionManager txManager) { TransactionInterceptor interceptor = new TransactionInterceptor(); interceptor.setTransactionAttributeSource(source); interceptor.setTransactionManager(txManager); return interceptor; }
@Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; try{ advisor = (BeanFactoryTransactionAttributeSourceAdvisor) this.beanFactory.getBean(TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME); BeanDefinition bd = this.beanFactory.getBeanDefinition(TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME); String adviceBeanName = (String) bd.getPropertyValues().getPropertyValue("adviceBeanName").getValue(); this.transactionInterceptor = (TransactionInterceptor) beanFactory.getBean(adviceBeanName); }catch(Exception ex){ //忽略这个异常,如果没有使用annotationDriver就将会出现的异常 } }
@Override protected void configure() { // TransactionManager bind(PlatformTransactionManager.class).toProvider(getPlatformTransactionManagerType()).in(Singleton.class); // TransactionInterceptor final TransactionInterceptor transactionInterceptor = new TransactionInterceptorEx(getProvider(PlatformTransactionManager.class), new AnnotationTransactionAttributeSource(false)); bindInterceptor(Matchers.any(), Matchers.annotatedWith(Transactional.class), transactionInterceptor); }
private BeanDefinition buildHibernateAdviceBeanDefinition(Element element, String name) { AbstractBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setAttribute(ID_ATTRIBUTE, name + HIBERNATE_ADVICE_SUFFIX); beanDefinition.setBeanClass(TransactionInterceptor.class); MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("transactionManager", new RuntimeBeanReference(name + HIBERNATE_TRANSACTION_MANAGER_SUFFIX)); propertyValues.add("transactionAttributeSource", new RuntimeBeanReference(name + TRANSACTION_ATTRIBUTE_SOURCE_SUFFIX)); beanDefinition.setPropertyValues(propertyValues); return beanDefinition; }
public void testRollbackRules() { TransactionInterceptor txInterceptor = (TransactionInterceptor) context.getBean("txRollbackAdvice"); TransactionAttributeSource txAttrSource = txInterceptor.getTransactionAttributeSource(); TransactionAttribute txAttr = txAttrSource.getTransactionAttribute(getAgeMethod,ITestBean.class); assertTrue("should be configured to rollback on Exception",txAttr.rollbackOn(new Exception())); txAttr = txAttrSource.getTransactionAttribute(setAgeMethod, ITestBean.class); assertFalse("should not rollback on RuntimeException",txAttr.rollbackOn(new RuntimeException())); }
/** * Creates a default transactional proxy for service with default transacction attributes * @param <T> * @param service * @return a Tx Proxy for service with default tx attributes */ @SuppressWarnings("unchecked") public <T> PersistentManager<T, Serializable> makeTransactionalProxy(PersistentManager<T, Serializable> service) { ProxyFactory factory = new ProxyFactory(service); factory.setInterfaces(new Class[] {Dao.class}); TransactionInterceptor interceptor = new TransactionInterceptor(transactionManager, new MatchAlwaysTransactionAttributeSource()); factory.addAdvice(interceptor); factory.setTarget(service); return (PersistentManager<T, Serializable>) factory.getProxy(); }
@Override protected Class<?> getBeanClass(Element element) { return TransactionInterceptor.class; }
public TransactionInterceptor create() { Properties props = new Properties(); props.put("tx_*", "PROPAGATION_REQUIRED"); return new TransactionInterceptor((DataSourceTransactionManager) getContext().getBean(TxManagerBox.class), props); }
@Bean public DefaultPointcutAdvisor defaultPointcutAdvisor(TransactionInterceptor transactionInterceptor, AspectJExpressionPointcut aspectJExpressionPointcut) { return new DefaultPointcutAdvisor(aspectJExpressionPointcut, transactionInterceptor); }
/** * Extracted in a protected method to facilitate testing */ protected void setRollbackOnly() { TransactionInterceptor.currentTransactionStatus().setRollbackOnly(); }
public TransactionInterceptor create() { Properties props = new Properties(); props.put("insert*", "PROPAGATION_REQUIRED"); return new TransactionInterceptor((DataSourceTransactionManager) getContext().getBean(TxManagerBox.class), props); }
@Override public void setUp() { this.ptm = new CallCountingTransactionManager(); this.source = new AnnotationTransactionAttributeSource(); this.ti = new TransactionInterceptor(this.ptm, this.source); }
@Override public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException { BeanDefinition bd = beanFactory.getBeanDefinition(TransactionInterceptor.class.getName() + "#0"); bd.setBeanClassName(DomainTransactionInterceptor.class.getName()); }
@Bean public TransactionInterceptor transactionInterceptorRealm() { return new TransactionInterceptor(transactionManagerRealm(), new AnnotationTransactionAttributeSource()); }