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

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

(1)配置数据源
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="${db_url}" />
<property name="username" value="$db_user}" />
<property name="password" value="${db_passwd}" />
<property name="maxWait" value="${db_maxWait}" />
<property name="maxActive" value="28" />
<property name="initialSize" value="2" />
<property name="minIdle" value="0" />
<property name="timeBetweenEvictionRunsMillis" value="db_time" />
</bean> (2)创建sqlSessionFactory
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath*:com/**/mapper/*Mapper*.xml" />
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.test.***.dal" />
</bean> (3)配置扫描器,扫描指定路径的mapper生成数据库操作代理类
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="annotationClass" value="javax.annotation.Resource"></property>
<property name="basePackage" value="com.test.***.dal.***.mapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean> (4)配置事务管理器
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> (5)声明使用注解式事务
<tx:annotation-driven transaction-manager="transactionManager" />
(6)注册各种beanfactory处理器
<context:annotation-config /> (7)该配置创建了一个TransactionInterceptor的bean,作为事务切面的执行方法
<tx:advice id="defaultTxAdvice">
<tx:attributes>
<tx:method name="*" rollback-for="Exception" />
</tx:attributes>
</tx:advice> (8)该配置创建了一个DefaultBeanFactoryPointcutAdvisor的bean,该bean是一个advisor,里面包含了pointcut和advice.前者说明切面加在哪里,后者是执行逻辑。此处可以配多个advisor
<aop:config>
<aop:pointcut id="myCut" expression="(execution(* *..*BoImpl.*(..))) "/>
<aop:advisor pointcut-ref="myCut" advice-ref="defaultTxAdvice" />
</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.3.1
//在bean注册到ioc后创建实例前修改bean定义和新增bean注册,这个是在context的refresh方法调用
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
1.3.2
//在bean注册到ioc后创建实例前修改bean定义或者属性值
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
1.3.3
//set属性设置后调用
void afterPropertiesSet() throws Exception;
1.3.4
//获取IOC容器上下文,在context的prepareBeanFactory中调用
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
1.3.5
//获取bean在ioc容器中名字,在context的prepareBeanFactory中调用
void setBeanName(String name);

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

screenshot.png

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

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

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

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
if (this.processPropertyPlaceHolders) {
processPropertyPlaceHolders();
} //构造一个ClassPathMapperScanner查找mapper
ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
scanner.setAddToConfig(this.addToConfig);
//javax.annotation.Resource
scanner.setAnnotationClass(this.annotationClass);
scanner.setMarkerInterface(this.markerInterface);
//引用sqlSessionFactory
scanner.setSqlSessionFactory(this.sqlSessionFactory);
scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
//ioc上下文
scanner.setResourceLoader(this.applicationContext);
scanner.setBeanNameGenerator(this.nameGenerator);
scanner.registerFilters();
//basePackage=com.alibaba.***.dal.***.mapper,com.alibaba.rock.auth.mapper,com.alibaba.rock.workflow.dal.workflow.mapper
scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}

下面重点看下scan方法:

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

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

 private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
GenericBeanDefinition definition;
for (BeanDefinitionHolder holder : beanDefinitions) {
definition = (GenericBeanDefinition) holder.getBeanDefinition(); // 上面讲的扫描后beanclass设置的为mapper接口类,但是这里修改为MapperFactoryBean,MapperFactoryBean代理了mapper接口类,并且实际mapper接口类作为构造函数传入了 definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName());
definition.setBeanClass(this.mapperFactoryBean.getClass());
definition.getPropertyValues().add("addToConfig", this.addToConfig); //设置属性配置中的sqlSessionFactory
boolean explicitFactoryUsed = false;
if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
explicitFactoryUsed = true;
} else if (this.sqlSessionFactory != null) {
definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
explicitFactoryUsed = true;
} if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
if (explicitFactoryUsed) {
logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
explicitFactoryUsed = true;
} else if (this.sqlSessionTemplate != null) {
if (explicitFactoryUsed) {
logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
explicitFactoryUsed = true;
} if (!explicitFactoryUsed) {
if (logger.isDebugEnabled()) {
logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
}
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
}
}
}

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

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

screenshot.png

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

  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
if (!this.externalSqlSession) {
this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
}
}

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

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

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

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

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

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

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

screenshot.png

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

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}

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

public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
PersistenceExceptionTranslator exceptionTranslator) { notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
notNull(executorType, "Property 'executorType' is required"); this.sqlSessionFactory = sqlSessionFactory;
this.executorType = executorType;
this.exceptionTranslator = exceptionTranslator;
this.sqlSessionProxy = (SqlSession) newProxyInstance(
SqlSessionFactory.class.getClassLoader(),
new Class[] { SqlSession.class },
new SqlSessionInterceptor());
}

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

 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//有TransactionSynchronizationManager管理
SqlSession sqlSession = getSqlSession(
SqlSessionTemplate.this.sqlSessionFactory,
SqlSessionTemplate.this.executorType,
SqlSessionTemplate.this.exceptionTranslator);
try {
Object result = method.invoke(sqlSession, args);
if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
// force commit even on non-dirty sessions because some databases require
// a commit/rollback before calling close()
sqlSession.commit(true);
}
return result;
} catch (Throwable t) {
.....
}
} public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { notNull(sessionFactory, NO_SQL_SESSION_FACTORY_SPECIFIED);
notNull(executorType, NO_EXECUTOR_TYPE_SPECIFIED); SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); SqlSession session = sessionHolder(executorType, holder);
if (session != null) {
return session;
} if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Creating a new SqlSession");
}
//这里看到了使用sessionfactory熟悉的打开了一个session
session = sessionFactory.openSession(executorType); registerSessionHolder(sessionFactory, executorType, exceptionTranslator, session); return session;
}

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

1.4 配置事务管理器

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

1.5 advice配置

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

screenshot.png

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

public class TxNamespaceHandler extends NamespaceHandlerSupport {

    static final String TRANSACTION_MANAGER_ATTRIBUTE = "transaction-manager";
static final String DEFAULT_TRANSACTION_MANAGER_BEAN_NAME = "transactionManager"; static String getTransactionManagerName(Element element) {
return (element.hasAttribute(TRANSACTION_MANAGER_ATTRIBUTE) ?
element.getAttribute(TRANSACTION_MANAGER_ATTRIBUTE) : DEFAULT_TRANSACTION_MANAGER_BEAN_NAME);
} @Override
public void init() {
registerBeanDefinitionParser("advice", new TxAdviceBeanDefinitionParser());
registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser());
registerBeanDefinitionParser("jta-transaction-manager", new JtaTransactionManagerBeanDefinitionParser());
} }

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

static final String DEFAULT_TRANSACTION_MANAGER_BEAN_NAME = "transactionManager";

static String getTransactionManagerName(Element element) {
return (element.hasAttribute(TRANSACTION_MANAGER_ATTRIBUTE) ?
element.getAttribute(TRANSACTION_MANAGER_ATTRIBUTE) : DEFAULT_TRANSACTION_MANAGER_BEAN_NAME);
}

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

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

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

1.6 设置advisor

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

screenshot.png

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

public class AopNamespaceHandler extends NamespaceHandlerSupport {

    @Override
public void init() {
registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser());
registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator()); registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
}
}

可知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源码知道:

public class BeanFactoryTransactionAttributeSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {

    private TransactionAttributeSource transactionAttributeSource;

    private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() {
@Override
protected TransactionAttributeSource getTransactionAttributeSource() {
return transactionAttributeSource;
}
};
}

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

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

public static void configureAutoProxyCreator(Element element, ParserContext parserContext) {
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element); String txAdvisorBeanName = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME;
//如果配置了多个注解式标签在datasource.xml里面时候只有第一个生效
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);
}
}

1.8 注册各种beanfactory处理器

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

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

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

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

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

public class ContextNamespaceHandler extends NamespaceHandlerSupport {

                ...
registerJava5DependentParser("annotation-config",
"org.springframework.context.annotation.AnnotationConfigBeanDefinitionParser");
....
} public class AnnotationConfigBeanDefinitionParser implements BeanDefinitionParser { public BeanDefinition parse(Element element, ParserContext parserContext) {
...
// Obtain bean definitions for all relevant BeanPostProcessors.
Set<BeanDefinitionHolder> processorDefinitions =
AnnotationConfigUtils.registerAnnotationConfigProcessors(parserContext.getRegistry(), source); // Register component for the surrounding <context:annotation-config> element.
CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
parserContext.pushContainingComponent(compDefinition); // Nest the concrete beans in the surrounding component.
for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
parserContext.registerComponent(new BeanComponentDefinition(processorDefinition));
} // Finally register the composite component.
parserContext.popAndRegisterContainingComponent(); return null;
} } public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, Object source) { Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>(4); // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
ClassLoader cl = AnnotationConfigUtils.class.getClassLoader();
def.setBeanClass(cl.loadClass(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
beanDefinitions.add(registerBeanPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
} // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
beanDefinitions.add(registerBeanPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
} if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
beanDefinitions.add(registerBeanPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
} if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
def.setSource(source);
def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
beanDefinitions.add(registerBeanPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
} return beanDefinitions;
}

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

原文地址:

http://ifeve.com/spring%E4%BA%8B%E5%8A%A1%E9%85%8D%E7%BD%AE%E8%A7%A3%E6%83%91/

spring+mybaits xml配置解析----转的更多相关文章

  1. spring的xml配置声明以及相应的问题处理

    spring的xml配置声明:  xml配置声明 Code 问题处理 问题1 xml报错: cvc-elt.1: Cannot find the declaration of element 'bea ...

  2. spring中用xml配置构造注入的心得

    spring中用xml配置构造注入时,如果 <constructor-arg> 属性都是 ref ,则不用理会参数顺序 <constructor-arg ref="kill ...

  3. Mybatis源码解析,一步一步从浅入深(三):实例化xml配置解析器(XMLConfigBuilder)

    在上一篇文章:Mybatis源码解析,一步一步从浅入深(二):按步骤解析源码 ,中我们看到 代码:XMLConfigBuilder parser = new XMLConfigBuilder(read ...

  4. ssm web.xml配置解析

    以下为web.xml的配置<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi=& ...

  5. Spring 基于XML配置

    基于XML的配置 对于基于XML的配置,Spring 1.0的配置文件采用DTD格式,Spring2.0以后采用Schema格式,后者让不同类型的配罝拥有了自己的命名空间,使得配置文件更具扩展性.此外 ...

  6. Spring MVC Xml视图解析器

    XmlViewResolver用于在xml文件中定义的视图bean来解析视图名称.以下示例演示如何在Spring Web MVC框架使用XmlViewResolver. XmlViewResolver ...

  7. Spring 中 Xml配置文件属性的说明

    Xml配置文件属性的说明: <bean id="TheAction" ⑴ class="net.xiaxin.spring.qs.UpperAction" ...

  8. Spring,SpringMvc配置常见的坑,注解的使用注意事项,applicationContext.xml和spring.mvc.xml配置注意事项,spring中的事务失效,事务不回滚原因

    1.Spring中的applicationContext.xml配置错误导致的异常 异常信息: org.apache.ibatis.binding.BindingException: Invalid ...

  9. spring ioc xml配置

    一个完整的spring xml配置:是把action,service,dao以及其它的资源性配置(如basedao)和公共性配置(如连接数据库)配置在resource.xml中,这样就有四个xml配置 ...

随机推荐

  1. 使用kafka和zookeeper 构建分布式编译环境

    1:在每台机器上安装jdk, 脚本代码如下: 每一个机器上下载jdk,zookeeper,kafka 链接:https://www.oracle.com/technetwork/java/javase ...

  2. static关键字(修饰函数、局部变量、全局变量)

    在C语言中,static的字面意思很容易把我们导入歧途,其实它的作用有三条. (1)先来介绍它的第一条也是最重要的一条:隐藏. 当我们同时编译多个文件时,所有未加static前缀的全局变量和函数都具有 ...

  3. Java语法基础学习DayNine(Java集合)

    一.Java集合 1.概述 一方面,面向对象语言对事物的体现都是以对象的形式,为了方便对多个对象的操作,就需要对对象进行存储.另一方面,使用Array存储对象具有一些弊端,而Java集合就像一种容器, ...

  4. SpringMVC学习二

    处理请求 今天学了三种请求,一种是 PathVariable ,一种是 RequestParam ,还有一种是CookieValue,并实现简单rest增删改查 上代码 package com.spr ...

  5. Linux:磁盘配额

    磁盘配额 一.简略步骤显示 第一步:关闭虚拟机 第二步:编辑虚拟机设置--硬盘--添加 第三步:查看磁盘分区情况 fdisk -l 第四步:选择磁盘分区 fdisk /dev/sda2 第五步:选择磁 ...

  6. IE6以下版本对元素width和height的处理与CSS标准的兼容性问题

    1.CSS使用width和height定义元素框的内容,Windows平台的IE6以下版本浏览器并未按照标准处理而是使用width和height来定义可见元素框的尺寸,IE/win使用width来描述 ...

  7. FCC JS基础算法题(8):Slasher Flick(截断数组)

    题目描述: 返回一个数组被截断n个元素后还剩余的元素,截断从索引0开始. 这个题目有两个方法,都比较简单,用slice方法: function slasher(arr, howMany) { // 请 ...

  8. 去掉 input type="number" 在浏览器中遗留的图标样式

    input::-webkit-outer-spin-button,input::-webkit-inner-spin-button{  /* chrome */     -webkit-appeara ...

  9. Kafka的安装 -- 未完成

    1. 官网下载软件 2. linux服务器上, 安装上传和下载的工具 yum install -y lrzsz rz : 上传 sz + 文件名 : 下载 3.解压文件 pwd: 查看当前路径 解压到 ...

  10. Vue实例data对象里允许有哪些类型数据

     做项目中遇到了data赋值的问题,总结了下常用的data赋值的数据类型.之前一直不确定是否能在data里写函数,实践证明data里也是可以对函数赋值的. export default { name: ...