欢迎转载,转载请注明出处:http://it.zhutibo.com/action/article1238.htm
概述:
Spring 特点:
- LightWeight(轻量级的):体积小、非入侵式的。
- Ioc(控制反转):对象不用自己创建查找依赖对象,而由容易进行注入。
- Aspect-oriented(面向切向):把应用需求的逻辑与系统公有特性分离,以切面的形式注入公有特性。
- Container(容器):创建bean并管理它们的生命周期。
- Framework(框架):Spring把应用程序通用的设计、模式抽象出来,我们仅需要以组件的形式开发并配置具体的应用逻辑。
Wiring beans/组织bean
BeanFactory vs. Application Context
Application Context相对于BeanFactory提供了更多的功能:
- 提从解析text messages的方法,并支持I18N
- 提供了通用的方法来加载文件资源(可能就是基于PostProcessor的对url的支持)
- 支持Spring各及事件的Listener支持。
Application Context中Bean的生命周期
XML wiring 语法
根结点
<beans> ... </beans>
创建一个bean
<bean id="xx" class="xx" singleton="false" init-method="xx" destroy-method="xx"/>
以Setter的形式注入依赖
<bean> <property name="xx"> <value>xx</value> || <ref bean="xx" /> || <bean class="xx" /> </property> </bean>
以Setter的形式注入依赖—注入容器
<list> | List, arrays |
<set> | set |
<map> | map |
<props> | Properties |
<null/> | null |
list | set | map | props |
<list> | <set> | <map> | <property name="xx"> |
以Constructor的形式注入依赖
<bean ...> <constructor-arg index="xx" type="xx"> <value> xx </value> || <ref bean="xx" /> </constructor-arg> ... </bean>
Auto Wiring | 自动组织
<bean ... autowire="byName | byType | constructor | autodetect" />
<beans default-autowire="byName">
- constructor:查找与构造函数参数类型一致的bean
- autodetect:选用constructor的方法,再用byType的方法
*注意:autowiring能够与显式的wiring一起使用。
特殊bean提供的额外功能
- 有关特殊:指实现了一些Spring预定的接口的bean,对于这些bean,Spring容器会对它们做出特别的处理,从而实现特别的功能,这些功能包含
- BeanPostProcessor:ApplicationContextPostProcessor、DefaultAdvisorAutoProxyCreator、PropertyResourceConfigurer
- BeanFactoryPostProcessor:调用时机:所有的bean定义加载完成,但尚未做任何实例化操作。
- PropertyResourceConfigurer:-->BeanPostProcessor, 属性location;语法${xx}
- PropertyEditorSupport:...>PropertyEditor. Spring自带:ClassEditor、CustomDateEditor、FileEditor、LocalEditor、StringArrayPropertyEditor、StringTrimmerEditor。
PropertyEditor的实现依赖于CustomEditorConfigurer属性:customEditors; - MessageSource:ResourceBundleMessageSource 属性basename,使用:context.getMessage(...); <spring:message code="xxx" />
- ApplicationListener:onApplicationEvent(); 分为:ApplicationEvent、及其子类:ContextClosedEvent、ContextRefreshedEvent、RequestHandledEvent
AOP总结
名词概念
- Aspect(切面):实现的横截功能
- Joinpoint(接入点):程序执行过程中的一个能加入横截功能的点
- Advice(通知):Aspect功能的实际代码实现时
- Pointcut(切入点):定义了advice将在哪一个joinpoint切入如程序中来。
- Introduction():?
- Target(目标类):被横截或代理的目标类。
- Proxy(代理类):已经植入advice功能的,与target接口相同的代理类
- weaving(切入过程):把advice应用到目标对象,并为它们创建代理的过程。
Advice种类
- Around:org.aopalliance.intercept.MethodInterceptor
- Before:org.springframework.aop.BeforeAdvice
- After:org.springframework.aop.AfterReturningAdvice
- Throws:org.springframework.aop.ThrowAdvice
Weaving切入过程语法
配置类:ProxyFactoryBean;
初始化属性:
- proxyInterfaces - Class[]
- interceptorNames - String[]
- target - Object
Pointcut定义语法
public interface Pointcut { ClassFilter getClassFilter(); MethodMatcher getMethodMatcher(); }
public interface ClassFilter { boolean matches(Class clazz); }
public interface MethodMatcher { boolean matches(Method m, Class targetClass); public boolean isRuntime(); public boolean matches(Method m, Class target, Object[] args); }
public interface PointcutAdvisor { Pointcut getPointcut(); Advice getAdvice(); }
NameMatchMethodPointcutAdvisor
初始化属性:
mappedName - String // methodNameCouldAppend*
mappedNames - String[]
RegExpPointcutAdvisor
注意:正则表达式配置的对象为"类名.方法名"
初始化属性:pattern
支持通配符:'.', '+', '*', '\'
自动代理AutoProxying
BeanNameAutoProxyCreator
将对符合名称表达式的所有bean添加动态代理,名称可以用通配符“*”。
初始化属性:
beanNames - String[]
interceptorNames -String[]
DefaultAdvisorAutoProxyCreator
将跟据Advisor中的pointcut定义,来决定给哪些Bean来创建代理。
Spring访问数据库 - JDBC篇
底层不相关异常DataAccessException
又分为好多子异常:。。。这里不例举了
Spring Dao 编程的一般模式
注意:Spring DaoTemplate(如JdbcTemplate)中,获取连接时,并不直接从DataSource中获取,而是封装在DataSourceUtils中,从而使每一次的连接获取,都与当前线程对应,同一个线程将一直获得同一个连接。
事务管理
先说下事务的四个特性:
Atomic(原子性)、Consistent(一致性)、Isolated(隔离性)、Durable(持久性)
编程式事务管理
transactionTemplate.execute( new TransactionCallback() { public Object doInTransaction(TransactionStatus ts) { try { // do stuff } catch (Exception e) { ts.setRollbackOnly(); } return null; } } );
必要配置
<bean id="transactionManager" class="org.springframework.jdbc. datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean>
<bean id="transactionTemplate" class="org.springframework. transaction.support.TransactionTemplate"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> </bean>
申明式事务管理
<bean id="courseService" class="org.springframework.transaction. interceptor.TransactionProxyFactoryBean"> <property name="proxyInterfaces"> <list> <value>com.springinaction.training.service.CourseService</value> </list> </property> <property name="target"> <ref bean="courseServiceTarget"/> </property> <property name="transactionManager"> <ref bean="transactionManager"/> </property> <property name="transactionAttributeSource"> <ref bean="attributeSource"/> </property> </bean>
事务属性
- Propagation behavior(渗透方式):MANDATORY、NESTED、NEVER、NOT_SUPPORTED、REQUIRED、REQUIRES_NEW、SUPPORTS
- Isolation levels(隔离等级):DEFAULT、READ_UNCOMMITTED、READ_COMMITTED、REPEATABLE_READ、SERIALIZABLE
- Read-only(只读优化):对确定仅查询的事务操作加上READ-ONLY会触发底层的性能优化。
- Transaction timeout(超时限制):~
MatchAlwaysTransactionAttributeSource
(by default, PROPAGATION_REQUIRED and ISOLATION_DEFAULT).
初始化属性:transactionAttribute
<bean id="myTransactionAttribute" class="org.springframework.transaction.interceptor. DefaultTransactionAttribute"> <property name="propagationBehaviorName"> <value>PROPAGATION_REQUIRES_NEW</value> </property> <property name="isolationLevelName"> <value>ISOLATION_REPEATABLE_READ</value> </property> </bean> <bean id="transactionAttributeSource" class="org.springframework.transaction.interceptor. MatchAlwaysTransactionAttributeSource"> <property name="transactionAttribute"> <ref bean="myTransactionAttribute"/> </property> </bean>
NameMatchTransactionAttributeSource
<bean id="transactionAttributeSource" class="org.springframework.transaction.interceptor. NameMatchTransactionAttributeSource"> <property name="properties"> <props> <prop key="enrollStudentInCourse*">PROPAGATION_REQUIRES_NEW</prop> </props> </property> </bean>
事性属性配置格式
关于回滚“-”,“+”
*注意:默认性况下,事务将在程序抛出“运行时异常”回滚。“-” 号表示在发现后缀异常时进行事务回滚
name-matched transactions 的精简型匹配方式
<bean id="courseService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> … <property name="transactionProperties"> <props> <prop key="enrollStudentInCourse"> PROPAGATION_REQUIRES_NEW </prop> </props> </property> </bean>
精简事务申明
申明的继承法(*比较推荐:即简洁,又明了)
<bean id="abstractTxDefinition" class="org.springframework.transaction.interceptor. TransactionProxyFactoryBean" lazy-init="true"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> <property name="transactionAttributeSource"> <ref bean="attributeSource"/> </property> </bean>
<bean id="courseService" parent="abstractTxDefinition"> <property name="target"> <bean class="com.springinaction.training.service.CourseServiceImpl"> </property> </bean>
事务的自动代理法
<bean id="autoproxy" class="org.springframework.aop.framework.autoproxy. DefaultAdvisorAutoProxyCreator"> … </bean>
<bean id="transactionAdvisor" class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor"> <constructor-arg> <ref bean="transactionInterceptor"/> </constructor-arg> </bean>
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> <property name="transactionAttributeSource"> <ref bean="transactionAttributeSource"/> </property> </bean>
选择合适的transactionAttributeSource
<bean id="transactionAttributeSource" class="org.springframework.transaction.interceptor.MethodMapTransactionAttributeSource"> <property name="methodMap"> <map> <entry key="com.springinaction.training.service.CourseServiceImpl.get*"> <value>PROPAGATION_SUPPORTS</value> </entry> </map> </property> </bean>
<bean id="transactionAttributeSource" class="org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource"> <property name="properties"> <props> <prop key="get*v>PROPAGATION_SUPPORTS</prop> </props> </property> </bean>