xmlns是xml namespace的缩写,也就是XML命名空间,xmlns 属性可以在文档中定义一个或多个可供选择的命名空间。今天小编要跟大家讲解的是Spring的命名空间配置。
首先,第一步要在xml中引用命名空间。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<!-- 引用命名空间的目的是为了使用tx与aop节点来配置事务管理器,与struts整合无关 -->
命名空间的内容可以从对应的jar包中找到,这里以AOP为例子说明,如图
在handlers和schemas文件即可找到对应的命名空间内容,根据所用的Spring 版本复制命名空间内容即可。
第二步,注册DBCP数据源一事务管理器
<!-- 注册DBCP数据源 -->
<bean id="dataSourceDBCP" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
<property name="username" value="scott"></property>
<property name="password" value="940909"></property>
</bean>
<bean id="testTransactionManagerId" //事务管理器Id可以用自己喜欢的名字命名
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSourceDBCP"></property>
</bean>
第三步,定义事务通知advice
<tx:advice id="userDaoId" transaction-manager="testTransactionManagerId">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" />//这里可以不是用通配的方法指定
</tx:attributes>
</tx:advice>
第四步,通过aop织入
<!-- 织入通知与切入点 (业务层实例方法要被插入事务管理的代码) -->
<aop:config>
<aop:pointcut expression="execution(* dao.imple.*.*(..))"
id="userDaoPointCut" />
<aop:advisor advice-ref="userDaoId" pointcut-ref="userDaoPointCut" />
</aop:config>
最后,就是编写业务层实例了
<bean id="userDao" class="dao.imple.TestUserDao">
<property name="dataSource" ref="dataSourceDBCP"></property>
</bean>
命名空间的配置到这里就大功告成了,注意在配置业务层实例时要使用对应接口的实现类。
另外小编再说一下命名空间的另一种配置--注解配置
注解配置首先要加载注解驱动<tx:annotation-driven transaction-manager="testTransactionManagerId" />
其次要在对应实现类的代码中加入@Transactional 标记 如图
最后也是要进行业务层实例的编写。
无论是注解配置还是通知配置,都各有好处,大家根据业务需要使用就好了。