当前位置:   article > 正文

Spring事务配置解惑_property 'basepackage' is required

property 'basepackage' is required

一、项目中spring+mybaits xml配置解析

一般我们会在datasource.xml中进行如下配置,但是其中每个配置项原理和用途是什么,并不是那么清楚,如果不清楚的话,在使用时候就很有可能会遇到坑,所以下面对这些配置项进行一一解说

  1. 1)配置数据源
  2. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
  3. <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
  4. <property name="url" value="${db_url}" />
  5. <property name="username" value="$db_user}" />
  6. <property name="password" value="${db_passwd}" />
  7. <property name="maxWait" value="${db_maxWait}" />
  8. <property name="maxActive" value="28" />
  9. <property name="initialSize" value="2" />
  10. <property name="minIdle" value="0" />
  11. <property name="timeBetweenEvictionRunsMillis" value="db_time" />
  12. </bean>
  13. 2)创建sqlSessionFactory
  14. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  15. <property name="mapperLocations" value="classpath*:com/**/mapper/*Mapper*.xml" />
  16. <property name="dataSource" ref="dataSource" />
  17. <property name="typeAliasesPackage" value="com.test.***.dal" />
  18. </bean>
  19. 3)配置扫描器,扫描指定路径的mapper生成数据库操作代理类
  20. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  21. <property name="annotationClass" value="javax.annotation.Resource"></property>
  22. <property name="basePackage" value="com.test.***.dal.***.mapper" />
  23. <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  24. </bean>
  25. 4)配置事务管理器
  26. <bean id="transactionManager"
  27. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  28. <property name="dataSource" ref="dataSource" />
  29. </bean>
  30. 5)声明使用注解式事务
  31. <tx:annotation-driven transaction-manager="transactionManager" />
  32. 6)注册各种beanfactory处理器
  33. <context:annotation-config />
  34. 7)该配置创建了一个TransactionInterceptor的bean,作为事务切面的执行方法
  35. <tx:advice id="defaultTxAdvice">
  36. <tx:attributes>
  37. <tx:method name="*" rollback-for="Exception" />
  38. </tx:attributes>
  39. </tx:advice>
  40. 8)该配置创建了一个DefaultBeanFactoryPointcutAdvisor的bean,该bean是一个advisor,里面包含了pointcut和advice.前者说明切面加在哪里,后者是执行逻辑。此处可以配多个advisor
  41. <aop:config>
  42. <aop:pointcut id="myCut" expression="(execution(* *..*BoImpl.*(..))) "/>
  43. <aop:advisor pointcut-ref="myCut" advice-ref="defaultTxAdvice" />
  44. </aop:config>

1.1 数据源配置

(1)是数据源配置,这个没啥好说的。

1.2 配置SqlSessionFactory

(2) 作用是根据配置创建一个SqlSessionFactory,看下SqlSessionFactoryBean的代码知道它实现了FactoryBean和InitializingBean类,由于实现了InitializingBean,所以自然它的afterPropertiesSet方法,由于实现了FactoryBean类,所以自然会有getObject方法。下面看下时序图:


screenshot.png

从时序图可知,SqlSessionFactoryBean类主要是通过属性配置创建SqlSessionFactory实例,具体是解析配置中所有的mapper文件放到configuration,然后作为构造函数参数实例化一个DefaultSqlSessionFactory作为SqlSessionFactory。

1.3 配置扫描器,扫描指定路径的mapper生成数据库操作代理类

MapperScannerConfigurer 实现了 BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware, BeanNameAware接口,所以会重写一下方法:

  1. 1.3.1
  2. //在bean注册到ioc后创建实例前修改bean定义和新增bean注册,这个是在context的refresh方法调用
  3. void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
  4. 1.3.2
  5. //在bean注册到ioc后创建实例前修改bean定义或者属性值
  6. void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
  7. 1.3.3
  8. //set属性设置后调用
  9. void afterPropertiesSet() throws Exception;
  10. 1.3.4
  11. //获取IOC容器上下文,在context的prepareBeanFactory中调用
  12. void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
  13. 1.3.5
  14. //获取bean在ioc容器中名字,在context的prepareBeanFactory中调用
  15. void setBeanName(String name);

先上个扫描mapper生成代理类并注册到ioc时序图:


screenshot.png

首先MapperScannerConfigurer实现的afterPropertiesSet方法用来确保属性basePackage不为空

  1. public void afterPropertiesSet() throws Exception {
  2. notNull(this.basePackage, "Property 'basePackage' is required");
  3. }

postProcessBeanFactory里面啥都没做,setBeanName获取了bean的名字,setApplicationContext里面获取了ioc上下文。下面看重要的方法postProcessBeanDefinitionRegistry,由于mybais是运行时候才通过解析mapper文件生成代理类注入到ioc,所以postProcessBeanDefinitionRegistry正好可以干这个事情。

  1. public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
  2. if (this.processPropertyPlaceHolders) {
  3. processPropertyPlaceHolders();
  4. }
  5. //构造一个ClassPathMapperScanner查找mapper
  6. ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
  7. scanner.setAddToConfig(this.addToConfig);
  8. //javax.annotation.Resource
  9. scanner.setAnnotationClass(this.annotationClass);
  10. scanner.setMarkerInterface(this.markerInterface);
  11. //引用sqlSessionFactory
  12. scanner.setSqlSessionFactory(this.sqlSessionFactory);
  13. scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
  14. scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
  15. scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
  16. //ioc上下文
  17. scanner.setResourceLoader(this.applicationContext);
  18. scanner.setBeanNameGenerator(this.nameGenerator);
  19. scanner.registerFilters();
  20. //basePackage=com.alibaba.***.dal.***.mapper,com.alibaba.rock.auth.mapper,com.alibaba.rock.workflow.dal.workflow.mapper
  21. scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
  22. }

下面重点看下scan方法:

  1. public Set<BeanDefinitionHolder> doScan(String... basePackages) {
  2. //根据指定路径去查找对应mapper的接口类,并转化为beandefination
  3. Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
  4. if (beanDefinitions.isEmpty()) {
  5. logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
  6. } else {
  7. //修改接口类bean的beandefination
  8. processBeanDefinitions(beanDefinitions);
  9. }
  10. return beanDefinitions;
  11. }

其中super.doScan(basePackages);根据指定路径查找mapper接口类,并生成bean的定义对象,对象中包含beanclassname,beanclass属性,最后注册该bean到ioc容器。下面看下最重要的processBeanDefinitions方法对bean定义的改造。

  1. private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
  2. GenericBeanDefinition definition;
  3. for (BeanDefinitionHolder holder : beanDefinitions) {
  4. definition = (GenericBeanDefinition) holder.getBeanDefinition();
  5. // 上面讲的扫描后beanclass设置的为mapper接口类,但是这里修改为MapperFactoryBean,MapperFactoryBean代理了mapper接口类,并且实际mapper接口类作为构造函数传入了 definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName());
  6. definition.setBeanClass(this.mapperFactoryBean.getClass());
  7. definition.getPropertyValues().add("addToConfig", this.addToConfig);
  8. //设置属性配置中的sqlSessionFactory
  9. boolean explicitFactoryUsed = false;
  10. if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
  11. definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
  12. explicitFactoryUsed = true;
  13. } else if (this.sqlSessionFactory != null) {
  14. definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
  15. explicitFactoryUsed = true;
  16. }
  17. if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
  18. if (explicitFactoryUsed) {
  19. logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
  20. }
  21. definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
  22. explicitFactoryUsed = true;
  23. } else if (this.sqlSessionTemplate != null) {
  24. if (explicitFactoryUsed) {
  25. logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
  26. }
  27. definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
  28. explicitFactoryUsed = true;
  29. }
  30. if (!explicitFactoryUsed) {
  31. if (logger.isDebugEnabled()) {
  32. logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
  33. }
  34. definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
  35. }
  36. }
  37. }

注:这里修改了mapper接口类的beandefination中的beanclass为MapperFactoryBean,它则负责生产数据类操作代理类,实际mapper接口类作为构造函数传入了 。由于只修改了beanclass,没有修改beanname,所以我们从容器中获取时候无感知的。

在上一个代理bean如何构造的时序图:


screenshot.png

下面看下MapperFactoryBean是如何生成代理类的:
首先,上面代码设置了MapperFactoryBean的setSqlSessionFactory方法:

  1. public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
  2. if (!this.externalSqlSession) {
  3. this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
  4. }
  5. }

上面方法创建了sqlSession,由于MapperFactoryBean为工厂bean所以实例化时候会调用getObject方法:

  1. public T getObject() throws Exception {
  2. return getSqlSession().getMapper(this.mapperInterface);
  3. }

其实是调用了SqlSessionTemplate->getMapper,其中mapperInterface就是创建MapperFactoryBean时候的构造函数参数。

  1. public <T> T getMapper(Class<T> type) {
  2. return getConfiguration().getMapper(type, this);
  3. }

这里调用getConfiguration().getMapper(type, this);实际是DefaultSqlSessionFactory里面的configration的getMapper方法:

  1. public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
  2. //knownMappers是上面时序图中步骤6设置进入的。
  3. final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
  4. if (mapperProxyFactory == null) {
  5. throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
  6. }
  7. try {
  8. return mapperProxyFactory.newInstance(sqlSession);
  9. } catch (Exception e) {
  10. throw new BindingException("Error getting mapper instance. Cause: " + e, e);
  11. }
  12. }
  13. protected T newInstance(MapperProxy<T> mapperProxy) {
  14. return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  15. }
  16. public T newInstance(SqlSession sqlSession) {
  17. //代理回调类为MapperProxy
  18. final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
  19. return newInstance(mapperProxy);
  20. }

在上一个实际执行sql时候调用代理类的序列图:


screenshot.png

所以当调用实际的数据库操作时候会调用MapperProxy的invoke方法:

  1. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  2. if (Object.class.equals(method.getDeclaringClass())) {
  3. try {
  4. return method.invoke(this, args);
  5. } catch (Throwable t) {
  6. throw ExceptionUtil.unwrapThrowable(t);
  7. }
  8. }
  9. final MapperMethod mapperMethod = cachedMapperMethod(method);
  10. return mapperMethod.execute(sqlSession, args);
  11. }

mapperMethod.execute(sqlSession, args);里面实际是调用当前mapper对应的SqlSessionTemplate的数据库操作,而它有委托给了代理类sqlSessionProxy,sqlSessionProxy是在SqlSessionTemplate的构造函数里面创建的:

  1. public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
  2. PersistenceExceptionTranslator exceptionTranslator) {
  3. notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
  4. notNull(executorType, "Property 'executorType' is required");
  5. this.sqlSessionFactory = sqlSessionFactory;
  6. this.executorType = executorType;
  7. this.exceptionTranslator = exceptionTranslator;
  8. this.sqlSessionProxy = (SqlSession) newProxyInstance(
  9. SqlSessionFactory.class.getClassLoader(),
  10. new Class[] { SqlSession.class },
  11. new SqlSessionInterceptor());
  12. }

所以最终数据库操作有被代理SqlSessionInterceptor执行:

  1. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  2. //有TransactionSynchronizationManager管理
  3. SqlSession sqlSession = getSqlSession(
  4. SqlSessionTemplate.this.sqlSessionFactory,
  5. SqlSessionTemplate.this.executorType,
  6. SqlSessionTemplate.this.exceptionTranslator);
  7. try {
  8. Object result = method.invoke(sqlSession, args);
  9. if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
  10. // force commit even on non-dirty sessions because some databases require
  11. // a commit/rollback before calling close()
  12. sqlSession.commit(true);
  13. }
  14. return result;
  15. } catch (Throwable t) {
  16. .....
  17. }
  18. }
  19. public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) {
  20. notNull(sessionFactory, NO_SQL_SESSION_FACTORY_SPECIFIED);
  21. notNull(executorType, NO_EXECUTOR_TYPE_SPECIFIED);
  22. SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
  23. SqlSession session = sessionHolder(executorType, holder);
  24. if (session != null) {
  25. return session;
  26. }
  27. if (LOGGER.isDebugEnabled()) {
  28. LOGGER.debug("Creating a new SqlSession");
  29. }
  30. //这里看到了使用sessionfactory熟悉的打开了一个session
  31. session = sessionFactory.openSession(executorType);
  32. registerSessionHolder(sessionFactory, executorType, exceptionTranslator, session);
  33. return session;
  34. }

注意:这里3里面配置的扫描文件在4的扫描文件里面一定要有,因为3给每个扫描文件生成了一个代理,如果4里面多了一个mapper,那么在4中将找不到。

1.4 配置事务管理器

事务管理器作用见名知意,是用来管理事务的。

1.5 advice配置

作用是创建了一个TransactionInterceptor的bean,作为事务切面的执行方法。标签解析的流程图:


screenshot.png

由于是tx标签,自然要查找TxNamespaceHandler,代码如下:

  1. public class TxNamespaceHandler extends NamespaceHandlerSupport {
  2. static final String TRANSACTION_MANAGER_ATTRIBUTE = "transaction-manager";
  3. static final String DEFAULT_TRANSACTION_MANAGER_BEAN_NAME = "transactionManager";
  4. static String getTransactionManagerName(Element element) {
  5. return (element.hasAttribute(TRANSACTION_MANAGER_ATTRIBUTE) ?
  6. element.getAttribute(TRANSACTION_MANAGER_ATTRIBUTE) : DEFAULT_TRANSACTION_MANAGER_BEAN_NAME);
  7. }
  8. @Override
  9. public void init() {
  10. registerBeanDefinitionParser("advice", new TxAdviceBeanDefinitionParser());
  11. registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser());
  12. registerBeanDefinitionParser("jta-transaction-manager", new JtaTransactionManagerBeanDefinitionParser());
  13. }
  14. }

从init方法知道advice标签需要TxAdviceBeanDefinitionParser这个解析类。
结合流程图第一步设置了事务管理器的引用,我们看下引用的bean的名字:

  1. static final String DEFAULT_TRANSACTION_MANAGER_BEAN_NAME = "transactionManager";
  2. static String getTransactionManagerName(Element element) {
  3. return (element.hasAttribute(TRANSACTION_MANAGER_ATTRIBUTE) ?
  4. element.getAttribute(TRANSACTION_MANAGER_ATTRIBUTE) : DEFAULT_TRANSACTION_MANAGER_BEAN_NAME);
  5. }

可以知道如果没有配置这个属性,那么默认查找依赖beanname=transactionManager。
然后parseAttributeSource主要循环解析我们配置的method标签,和设置的方法的事务属性。
另外代码:

  1. protected Class<?> getBeanClass(Element element) {
  2. return TransactionInterceptor.class;
  3. }

可以知道这个advice标签实际是创了TransactionInterceptor对象,并且通过调用setTransactionManager设置了事务管理器,通过setTransactionAttributeSources设置了事务属性。

1.6 设置advisor

标签<aop:config>作用是创建了DefaultBeanFactoryPointcutAdvisor作为拦截器,把满足切点的bean进行代理使用事务拦截器进行拦截。具体标签逻辑先看流程图:


screenshot.png

从标签<aop:config>可知要查找AopNamespaceHandler,代码如下:

  1. public class AopNamespaceHandler extends NamespaceHandlerSupport {
  2. @Override
  3. public void init() {
  4. registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser());
  5. registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
  6. registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator());
  7. registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
  8. }
  9. }

可知config标签是ConfigBeanDefinitionParser来解析的,根据流程图知configureAutoProxyCreator注册了AspectJAwareAdvisorAutoProxyCreator类,然后createAdvisorBeanDefinition创建了DefaultBeanFactoryPointcutAdvisor,它是个advisor,并且设置引用了advice,这个adivce就是上面1.5讲解的,然后createPointcutDefinition创建了切点AspectJExpressionPointcut,最后把切点设置到了advisor。
DefaultBeanFactoryPointcutAdvisor作用就是对满足pointcut表达式的类的方法进行代理,并且使用advice进行拦截处理,而advice就是事务拦截器。

1.7 设置注解式事务

上面介绍完后就可以使用事务切面了,但是有时候还需要在具体类或者方法上进行注解行事务,那么这就需要加 <tx:annotation-driven transaction-manager="transactionManager" />配置
先上时序图:


screenshot.png

!
同理1.6 不同是这里创建了advisor,设置了advice(事务拦截器),但是好像没有设置pointcut,看下BeanFactoryTransactionAttributeSourceAdvisor源码知道:

  1. public class BeanFactoryTransactionAttributeSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {
  2. private TransactionAttributeSource transactionAttributeSource;
  3. private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() {
  4. @Override
  5. protected TransactionAttributeSource getTransactionAttributeSource() {
  6. return transactionAttributeSource;
  7. }
  8. };
  9. }

直接内置了pointcut,只不过1.6是AspectJExpressionPointcut表达式的切点,这里是注解。
那么这个BeanFactoryTransactionAttributeSourceAdvisor什么时候被用来增强注解事务的类那,那是InfrastructureAdvisorAutoProxyCreator所做的事情,InfrastructureAdvisorAutoProxyCreator是个BeanPostProcessor,会在bean创建初始化后时候调用postProcessAfterInitialization,就是这个方法。

另外注意如果配置了多个注解式标签在datasource.xml里面时候只有第一个生效

  1. public static void configureAutoProxyCreator(Element element, ParserContext parserContext) {
  2. AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element);
  3. String txAdvisorBeanName = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME;
  4. //如果配置了多个注解式标签在datasource.xml里面时候只有第一个生效
  5. if (!parserContext.getRegistry().containsBeanDefinition(txAdvisorBeanName)) {
  6. Object eleSource = parserContext.extractSource(element);
  7. // Create the TransactionAttributeSource definition.
  8. RootBeanDefinition sourceDef = new RootBeanDefinition(
  9. "org.springframework.transaction.annotation.AnnotationTransactionAttributeSource");
  10. sourceDef.setSource(eleSource);
  11. sourceDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  12. String sourceName = parserContext.getReaderContext().registerWithGeneratedName(sourceDef);
  13. // Create the TransactionInterceptor definition.
  14. RootBeanDefinition interceptorDef = new RootBeanDefinition(TransactionInterceptor.class);
  15. interceptorDef.setSource(eleSource);
  16. interceptorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  17. registerTransactionManager(element, interceptorDef);
  18. interceptorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName));
  19. String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef);
  20. // Create the TransactionAttributeSourceAdvisor definition.
  21. RootBeanDefinition advisorDef = new RootBeanDefinition(BeanFactoryTransactionAttributeSourceAdvisor.class);
  22. advisorDef.setSource(eleSource);
  23. advisorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  24. advisorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName));
  25. advisorDef.getPropertyValues().add("adviceBeanName", interceptorName);
  26. if (element.hasAttribute("order")) {
  27. advisorDef.getPropertyValues().add("order", element.getAttribute("order"));
  28. }
  29. parserContext.getRegistry().registerBeanDefinition(txAdvisorBeanName, advisorDef);
  30. CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), eleSource);
  31. compositeDef.addNestedComponent(new BeanComponentDefinition(sourceDef, sourceName));
  32. compositeDef.addNestedComponent(new BeanComponentDefinition(interceptorDef, interceptorName));
  33. compositeDef.addNestedComponent(new BeanComponentDefinition(advisorDef, txAdvisorBeanName));
  34. parserContext.registerComponent(compositeDef);
  35. }
  36. }

1.8 注册各种beanfactory处理器

当我们需要使用BeanPostProcessor时,最直接的使用方法是在Spring配置文件中定义这些Bean。单这些会显得比较笨拙,
例如:使用@Autowired注解,必须事先在Spring容器中声明

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/>

使用 @Required注解,就必须声明:

  1. <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

通过标签<context:annotation-config/> ,我们可以同时自动注册这些常用的beanfactory处理器,避免了我们一个个配置的繁琐步骤:

  1. public class ContextNamespaceHandler extends NamespaceHandlerSupport {
  2. ...
  3. registerJava5DependentParser("annotation-config",
  4. "org.springframework.context.annotation.AnnotationConfigBeanDefinitionParser");
  5. ....
  6. }
  7. public class AnnotationConfigBeanDefinitionParser implements BeanDefinitionParser {
  8. public BeanDefinition parse(Element element, ParserContext parserContext) {
  9. ...
  10. // Obtain bean definitions for all relevant BeanPostProcessors.
  11. Set<BeanDefinitionHolder> processorDefinitions =
  12. AnnotationConfigUtils.registerAnnotationConfigProcessors(parserContext.getRegistry(), source);
  13. // Register component for the surrounding <context:annotation-config> element.
  14. CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
  15. parserContext.pushContainingComponent(compDefinition);
  16. // Nest the concrete beans in the surrounding component.
  17. for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
  18. parserContext.registerComponent(new BeanComponentDefinition(processorDefinition));
  19. }
  20. // Finally register the composite component.
  21. parserContext.popAndRegisterContainingComponent();
  22. return null;
  23. }
  24. }
  25. public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
  26. BeanDefinitionRegistry registry, Object source) {
  27. Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>(4);
  28. // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
  29. if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  30. RootBeanDefinition def = new RootBeanDefinition();
  31. try {
  32. ClassLoader cl = AnnotationConfigUtils.class.getClassLoader();
  33. def.setBeanClass(cl.loadClass(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME));
  34. }
  35. catch (ClassNotFoundException ex) {
  36. throw new IllegalStateException(
  37. "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
  38. }
  39. def.setSource(source);
  40. def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  41. beanDefinitions.add(registerBeanPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
  42. }
  43. // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
  44. if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  45. RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
  46. def.setSource(source);
  47. def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  48. beanDefinitions.add(registerBeanPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
  49. }
  50. if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  51. RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
  52. def.setSource(source);
  53. def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  54. beanDefinitions.add(registerBeanPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
  55. }
  56. if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  57. RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
  58. def.setSource(source);
  59. def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  60. beanDefinitions.add(registerBeanPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
  61. }
  62. return beanDefinitions;
  63. }

主要注册常用的:
RequiredAnnotationBeanPostProcessor
AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
平时我们使用autowired或者required之所以能生效,就是因为这个自动注入ioc已经。

总结

本文是作者经验所写,由于作者水平有限,难免出错,希望童鞋们批评指正,共同学习。


欢迎关注微信公众号:技术原始积累 获取更多技术干货

image.png


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/892572
推荐阅读
相关标签
  

闽ICP备14008679号