1、使用XML配置声明式事务
public interface BbtTopic{
void addTopic(Topic topic);
int getTopicNum();
}
public class BbtTopicImpl implements BbtTopic{
private TopicDao topicDao;
public void addTopic(Topic topic){
topicDao.addTopic(topic);
}
public int getTopicNum(){
return topicDao.getTopicNum();
}
}
我们希望对addTopic()添加写事务功能,对getTopicNum()提供读事务功能,配置如下:
首先添加tx和aop命名空间
<bean id="bbtTopic" class="xxx.xxx.BbtTopicImpl"
p:topicDao-ref="topicDao"> //引用DAO
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource">//引用数据源
</bean>
<aop:config>
//将xxx.xxx.service包下以Topic结尾的类纳入进行事务增强的范围
<aop:pointcut id="serviceMethod" expression="execution(* xxx.xxx.service.*Topic.*(..))"/>
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice">
</aop:config>
<tx:advice id="txAdivce" transaction-manager="txManager">
<tx.attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="add*" rollback-for="Exception"/>
</tx.attributes>
</tx:advice>
2、使用注解配置声明式事务
(1)对实现类添加@Transactional
public interface BbtTopic{
void addTopic(Topic topic);
int getTopicNum();
}
@Transactional
public class BbtTopicImpl implements BbtTopic{
private TopicDao topicDao;
public void addTopic(Topic topic){
topicDao.addTopic(topic);
}
public int getTopicNum(){
return topicDao.getTopicNum();
}
}
(2)xml配置
<bean id="bbtTopic" class="xxx.xxx.BbtTopicImpl"
p:topicDao-ref="topicDao"> //引用DAO
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource">//引用数据源
</bean>
<tx:annotation-driven transaction-manager="txManager"/> //proxy-target-class="false|true"