applicationContext.xml 重识
从整体上来看该xml文件相当于是一个内容很大的类,只不过相比于一般的类来说。配置性东西很多,要更加灵活。
spring文件最外层的beans
感觉像是申明一样的东西,查阅后说是申明 命名空间,感觉像是在一个实体中声明,为了后面使用,一些特殊开头的标签使用时都需要先有这些才行。
最外层
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
">
</beans>
注意开头的
context
xsi
tx
aop
schemaLocation
都是为了使用特殊标签的声明,声明命名空间
bean
在spring配置文件中,主要的就是bean标签,主要用来声明和注入一些类,配置的,实体的,外部引用时的template实体,等等都是以bean的形式,这个不多赘述了,可参考这篇基础的
spring初步
事务声明方式
用到了上面声明的 tx
先声明事务类
Hibernate类型的参考如下
<!-- 配置Hibernate事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
Mybatis的参考(JDBCTemplate与此一致)
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
若要开启事务注解 则添加
<tx:annotation-driven />
或
<tx:annotation-driven transaction-manager="transactionManager"/>
transaction-manager中的是事务类的bean对应的id
声明事务属性
transaction-manager同样为事务管理的bean的id
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" propagation="REQUIRED" rollback-for="类似于com.aurora.**形式" />
<tx:method name="create*" isolation="SERIALIZABLE" propagation="REQUIRED" rollback-for="类似于com.aurora.**形式" />
<tx:method name="query*" propagation="REQUIRED" rollback-for="类似于com.aurora.**形式" />
</tx:attributes>
</tx:advice>
isolation 隔离级别
propagation 传播机制
rollback-for 回滚
配置事务aop织入
expose-proxy=“true” 不需要可以不写
与上面一致的例子为一套
<aop:config expose-proxy="true">
<aop:pointcut id="txPointcut" expression="(execution(* com.aurora.app.core..*.*(..)) or execution(* com.aurora.app.service..*.*(..))
or execution(* com.aurora.app.manager..*.*(..)))
and not execution(* com.aurora.service.AService.*(..)) and not execution(* com.aurora.service.BService.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
表达式可以只写一个,如果不需要多个
aop注入若报错
则加入
<aop:aspectj-autoproxy proxy-target-class="true"/>
为true 为cglig代理 flase为jdk动态代理
可能报如下错误
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type
或
java.lang.ClassCastException: com.sun.proxy.$Proxy12 cannot be cast to cn.edu.nuc.SpringTest.service.impl.DemoServiceImpl