Springboot integration affairs from spring to spring to achieve the principles of the transaction

Disclaimer: This article is a blogger original article, please indicate the source. https://blog.csdn.net/u010597819/article/details/88750491

Enable spring Affairs

  1. @EnableTransactionManagement, yes as long as the transaction manager to enable the increase of the notes to the spring Affairs to take effect, of course, also need to implement the transaction transaction manager
  2. Enter "enable transaction notes," we can see inside the introduction of import-related configuration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {
  1. You can see the introduction of TransactionManagementConfigurationSelector, meaning the class can see the bloggers another article ( springboot Annotation-spring-IOC-source learning ) has detailed the entire spring loading process of the bean, which contains import selector class, I will direct its role will be, in fact, carried out by the annotation configuration import bean, the default mode is the annotation proxy, which is a proxy mode, will ProxyTransactionManagementConfiguration and AutoProxyRegistrar registered to the factory
  @Override
	protected String[] selectImports(AdviceMode adviceMode) {
		switch (adviceMode) {
			case PROXY:
				return new String[] {AutoProxyRegistrar.class.getName(),
						ProxyTransactionManagementConfiguration.class.getName()};
			case ASPECTJ:
				return new String[] {
						TransactionManagementConfigUtils.TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME};
			default:
				return null;
		}
	}
  1. The annotation AutoProxyRegistrar class configuration InfrastructureAdvisorAutoProxyCreator (SmartInstantiationAwareBeanPostProcessor) Post-processing registers to the plant
  2. ProxyTransactionManagementConfiguration configuration class is a class, the major provide BeanFactoryTransactionAttributeSourceAdvisor, transactionAttributeSource, transactionInterceptor three bean introduced, the specific role of the back 3 will further specific discussion of bean
  3. At this point the entire process to enable transaction successfully completed

Configured to use spring Affairs

  1. springboot has been automatically integrated configuration spring affairs, that is, we no longer need to configure a special spring affairs, can be used directly, that is used directly @Transactional, then we take a look at how springboot is automatically configured for our
  2. Then we have to catch up with the spring-boot-autoconfigure-1.5.19.RELEASE.jar inside a transaction module: org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, then we still has some windfall Oh
  3. See the contents of the automatic configuration class, we found a static inner class EnableTransactionManagementConfiguration, we found it is automatically configured to enable the transaction to us, that we often see a problem before it was mentioned in the forums, or blog, is why I do not have to configure @EnableTransactionManagement, but the transaction is still in effect, if you are used to project the springboot, which undoubtedly is a possibility
  @Configuration
	@ConditionalOnBean(PlatformTransactionManager.class)
	@ConditionalOnMissingBean(AbstractTransactionManagementConfiguration.class)
	public static class EnableTransactionManagementConfiguration {

		@Configuration
		@EnableTransactionManagement(proxyTargetClass = false)
		@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = false)
		public static class JdkDynamicAutoProxyConfiguration {

		}

		@Configuration
		@EnableTransactionManagement(proxyTargetClass = true)
		@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = true)
		public static class CglibAutoProxyConfiguration {

		}

	}
  1. Back to the topic, we can see that the class has been configured to automatically configure the transaction manager DataSourceTransactionManagerAutoConfiguration for us, you can see inside the default DataSourceTransactionManager achieve
		@Bean
		@ConditionalOnMissingBean(PlatformTransactionManager.class)
		public DataSourceTransactionManager transactionManager(
				DataSourceProperties properties) {
			DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(
					this.dataSource);
			if (this.transactionManagerCustomizers != null) {
				this.transactionManagerCustomizers.customize(transactionManager);
			}
			return transactionManager;
		}
  1. So far we have ended our springboot automatically integrated spring configuration transaction process, playing call it for themselves _ !!!

The principle spring Affairs

From the previous two sections we learned how to use the spring Affairs in springboot project, but also simple to understand springboot how to automatically configure our affairs, here we inevitably wonder how spring of transactions is achieved, of course, many people may first reaction springAOP it is used, yes, yes, exactly how so woven into the code? Let me further opened its mysterious veil it, HIAHIAHIA. . .
If you have read spring source person should have to understand, the life cycle of a bean, do not know if you can go to the above-mentioned bloggers blog post view detailed loading process, of course, there are bloggers streamlined summary version ( the Spring IOC load summary )

  1. Our breakthrough of course, is to use the bean initialization process transactions. Can find the answer from the use of bean initialization process transactions, you can locate and navigate to specific points through debug breakpoint way
  2. Which is not described in detail, transaction codes spring weaving point is performed in post-processing (postProcessAfterInitialization) bean after initialization is complete, i.e. InfrastructureAdvisorAutoProxyCreator, this is the right EnableTransactionManagement annotation AutoProxyRegistrar arranged inside the factory to register registerBeanDefinitions (AopConfigUtils. registerAutoProxyCreatorIfNecessary )
  3. InfrastructureAdvisorAutoProxyCreator parent class method postProcessAfterInitialization, if the bean does not contain a cache, if you must specify the package, if there is a corresponding notification Advisor is to create a proxy
  4. InfrastructureAdvisorAutoProxyCreator parent class method getAdvicesAndAdvisorsForBean, find a qualified advisor notice findEligibleAdvisors
  5. Find all Advisor from the factory to achieve bean, that is, contains configuration before: BeanFactoryTransactionAttributeSourceAdvisor
  6. According beanName set the flag, the flag of the current proxy is being created, the release is after the completion of ProxyCreationContext. SetCurrentProxiedBeanName (beanName);
  7. Obtaining the corresponding notification agent according to the bean class list AopUtils. FindAdvisorsThatCanApply (candidateAdvisors, beanClass);
  8. Determining whether the application can be AopUtils.canApply
  9. If IntroductionAdvisor type of notification, the strong get into IntroductionAdvisor type ClassFilter determine whether matching matches, if it returns true then the match is qualified to be returned into a collection notice
  10. If notice is not qualified at this time it is empty, indicating hasIntroductions is true, according to continue to find hasIntroductions
  11. If the notification is PointcutAdvisor type (that is, before the automatic configuration of the type of notification)
  12. Strong and get into PointcutAdvisors continue to determine Pointcut
  13. Pointcut get ClassFilter determine whether matching matches, the match continues
  14. Pointcut get MethodMatcher, if it is MethodMatcher. TRUE returns true example of that match as a qualified notice
  15. If MethodMatcher is IntroductionAwareMethodMatcher type, strong turn IntroductionAwareMethodMatcher
  16. All interfaces and their method of traversing a target class determining method returns true if introductionAwareMethodMatcher matches or matching method for matching determination matches methodMatcher
  17. Notification list and ordering the return of qualified
  18. If there is a proxy notice the logo is being created
  19. Creating an agent createProxy
  20. If the plant is ConfigurableListableBeanFactory type, the agent was added _ORIGINAL_TARGET_CLASS_ATTRIBUTE attribute value of the target bean definition class_
  21. Create a proxy factory ProxyFactory, and copy ProxyConfig configuration (proxyTargetClass, optimize, exposeProxy, frozen, opaque)
  22. If proxyTargetClass configured as false, and bean _PRESERVE_TARGET_CLASS_ATTRIBUTE attribute definition is false is executed _evaluateProxyInterfaces, or re-set to true proxyTargetClass
  23. Construction of notification buildAdvisors
  24. Access to public notice interceptorNames: the Default IS NO the Common interceptors, the default is empty
  25. If public notification is not empty and is set to applyCommonInterceptorsFirst, then placed to intercept the front, back or put
  26. Traversing all interfaces to intercept the package and create a corresponding notice: advisorAdapterRegistry.wrap: If you are the type of notification Advisor direct return, if it is packaged as MethodInterceptor type DefaultPointcutAdvisor return, if the call is AdvisorAdapter type adapter type supportsAdvice determine whether the type of support, and if so, return
  27. Back to News List
  28. Set advisors, targetSource, freezeProxy, if advisorsPreFiltered, preFiltered is set to true ProxyFactory
  29. Creating an agent getProxy according to proxyClassLoader
  30. Creating AOP proxy createAopProxy, inform the listener AdvisedSupportListener.activated
  31. Get aopProxyFactory factory creates proxy createAopProxy: The default is JdkDynamicAopProxy, if the target class is not an interface and not the Proxy agent is used ObjenesisCglibAopProxy
  32. Acting factory to create a proxy JdkDynamicAopProxy.getProxy, InvocationHandler current instance JdkDynamicAopProxy
  33. Returns the proxy bean
  34. So far we learned how to implement the transaction and spring aop, yes it is a dynamic agency, let's continue to look at how jdk agent for the transaction is packed spring

spring Affairs jdk dynamic proxy implementation principle

  1. JdkDynamicAopProxy achieve
  2. If it equals methods such as direct return target calls
  3. Get notifications interceptor chain chain: advised.getInterceptorsAndDynamicInterceptionAdvice (method, targetClass), advised that is ProxyConfig is ProxyFactory
  4. If the chain is empty interceptor directly reflected call (so performance is achieved than cglib bytecode poor performance of some embodiment)
  5. If empty, the package is not interceptor chain ReflectiveMethodInvocation call proceed
  6. If the call is the last call chain node (currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size () - 1) calls directly reflected invokeJoinpoint
  7. Otherwise, get currentInterceptorIndex index from interceptorsAndDynamicMethodMatchers instance of call and increment currentInterceptorIndex
  8. If the type is acquired methodMatcher InterceptorAndDynamicMethodMatcher match is determined whether the corresponding call interceptor.invoke (this). If not then proceed directly to the next node proceed to call
  9. If not InterceptorAndDynamicMethodMatcher type into the strong MethodInterceptor calling invoke (this)
  10. We comment further look spring Affairs interceptor that is mentioned earlier in automatic configuration TransactionInterceptor
  11. You can see after the call will continue to call the next node in the callback interceptor (ie nested scenarios transaction), this is the parameter of the recursive call, the object will get incremented currentInterceptorIndex
  12. Call interceptor method invokeWithinTransaction contain Affairs
  13. TransactionAttributeSource transaction attribute acquisition source, i.e. AnnotationTransactionAttributeSource, certain analytical method transaction attribute getTransactionAttribute, for example: SpringTransactionAnnotationParser parser annotation corresponding to the attribute
  14. Configuring acquisition in accordance with the transaction attributes corresponding transaction manager (will get a transaction manager from the cache when the actual call, if there is no will get a corresponding transaction manager Depending on the configuration, is not necessary to wait for the transaction manager loaded), so the configuration we see if the transaction manager is not set to empty, empty what impact there will be no
  @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;
	}
  1. Property is not empty and is CallbackPreferringPlatformTransactionManager type of transaction manager into the type of tasks execute CallbackPreferringPlatformTransactionManager
  2. The default automatic configuration for DataSourceTransactionManager, not CallbackPreferringPlatformTransactionManager type.
  3. Try to create a transaction, if needed createTransactionIfNecessary, obtain transaction status TransactionStatus from tm (Transaction Manager)
  4. Get the transaction status AbstractPlatformTransactionManager.getTransaction tm call parent class method, obtaining the definition of the transaction from the transaction getTransaction (i.e., transaction attribute)
  5. doGetTransaction create DataSourceTransactionObject (transaction instance) to bind to the current connectionHolder
  6. Determining whether there is a transaction, it is determined whether transactionActive is true, then the present transmission properties according to the encapsulated transaction return to the transaction state handleExistingTransaction.
  7. If the transfer type is _PROPAGATION_NEVER, an exception is thrown: _IllegalTransactionStateException ( "Existing transaction found for transaction marked with propagation 'never'")
  8. If the transmission type is _PROPAGATION_NOT_SUPPORTED, the transaction Transaction blanking, and the latter corresponding to bind that bind to suspend the current transaction is executed in a non-transactional method, after post-processing is performed after completion of the current transaction and then restore into the next interception CCN _
  9. If the transfer type is _PROPAGATION_REQUIRES_NEW, the New Transaction _
  10. If the delivery type is a nested _PROPAGATION_NESTED_: If you allow save_point way to implement nested transactions (Transaction Manager nested transaction spring, usually JDBC3.0), then create a savepoint; otherwise use begin commit / rollback manner (using nested transactions achieve JTA)
  11. After the transfer of other types, the new transaction is identified as a non return (i.e. newTransaction = false)
  12. There is no transaction, transfer type _PROPAGATION_MANDATORY exception is thrown: _IllegalTransactionStateException ( "No existing transaction found for transaction marked with propagation 'mandatory'")
  13. The absence of a transaction and transmission of _PROPAGATION_REQUIRED, PROPAGATION_REQUIRES_NEW, PROPAGATION_NESTED one; the new transaction _DefaultTransactionStatus, doBegin: set to false automatically submit a series of operations; prepareSynchronization: prepare a transaction manager and bind the synchronous transaction attributes configuration, initialization, (create a new transaction synchronization TransactionSynchronization generic list, mainly for synchronized action callbacks in some state affairs point), return to the state of affairs
  14. prepareTransactionInfo: According to the state of affairs as a package transaction information and transaction information ready, and bound to the current thread, return transaction information (in fact, with the current thread binding bindToThread)
  15. I.e., recursive call callback interceptor next node (or actual nested transactions method)
  16. cleanupTransactionInfo currently executing node to complete: restore bindings on nodes transaction information restoreThreadLocalStatus
  17. After completion of the return value and return the interceptor performs the processing chain submitted commitTransactionAfterReturning
  18. The rollback transaction processing or commit state
  19. Transaction commits
  20. If there save_points, releasing save point (ie after submission save point to save point blank)
  21. If you are a new transaction (description of all nodes are intercepted chain execution is complete), direct access to the connection handle commit submit
  22. Return target calling method return values
  23. A series of post-action: Clear identification and notification if there is a callback

summary

  1. spring nested transactions for implementation in two ways, one is added every time a save point, one is to use begin end fashion
  2. If you open a checking existing transaction, each acquiring an existing transaction isolation level will verify whether it is consistent with the parent isolation level, if not an exception is thrown IllegalTransactionStateException, if READONLY attributes do not match, an exception is thrown the same throw IllegalTransactionStateException
  3. TransactionSynchronizationManager manage synchronization notification, each node if you want to monitor the status of the transaction can be achieved through the synchronization interface and register to Manager

Transaction Lifecycle

Transaction Lifecycle

Guess you like

Origin blog.csdn.net/u010597819/article/details/88750491