ASPECTJ Declarative Transaction Configuration

Source: Internet
Author: User

Spring declarative transaction configuration for the simulation transfer process (AspectJ)

Programmatic transactions to modify the service layer's code, in contrast, AspectJ enhanced transaction Manager, configuration of tangent points (AOP) in XML, and service code without modification.

1. New data table

DROP TABLE IF EXISTS ' account '; CREATE TABLE ' account ' (' id ' int (one) not null auto_increment, ' name ' varchar () ' is not null ', ' money ' double unsigned Zer Ofill default NULL, PRIMARY KEY (' id ')) engine=innodb auto_increment=4 default Charset=utf8;insert into ' account ' VALUES (' 1 ', ' AA ', ' + '); INSERT into ' account ' values (' 2 ', ' BB ', ' ' + '); INSERT into ' account ' values (' 3 ', ' cc ', ' 1000 ');

2. Create a new project and introduce a jar package

<dependency><groupid>org.apache.commons</groupid><artifactid>commons-lang3</ artifactid><version>3.4</version></dependency><dependency><groupid>log4j</                     Groupid><artifactid>log4j</artifactid><version>1.2.17</version></dependency> <dependency><groupid>junit</groupid><artifactid>junit</artifactid><version >4.12</version><scope>test</scope></dependency><!--MySQL driver--><dependency ><groupid>mysql</groupid><artifactid>mysql-connector-java</artifactid><version >5.1.6</version></dependency> <!--Spring--><dependency><groupid>or g.springframework</groupid><artifactid>spring-context</artifactid><version>4.2.1. Release</version></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-core</artifactid><version>4.2.1.release</version></ Dependency><dependency><groupid>org.springframework</groupid><artifactid> Spring-beans</artifactid><version>4.2.1.release</version></dependency><dependency ><groupId>org.springframework</groupId><artifactId>spring-expression</artifactId> <version>4.2.1.RELEASE</version></dependency><dependency><groupId> org.springframework</groupid><artifactid>spring-jdbc</artifactid><version>4.2.1. Release</version></dependency><dependency><groupid>org.springframework</groupid> <artifactId>spring-tx</artifactId><version>4.2.0.RELEASE</version></dependency> <dependency><groupid>org.springframework</groupid><artifactid>spring-test</ Artifactid><version>4.2.1.release</version></dependency><dependency><groupid>org.springframework</groupid><artifactid> Spring-aop</artifactid><version>4.2.1.release</version></dependency><dependency> <groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId>< version>4.2.1.release</version></dependency><!--Spring End--><!--c3p0-->< Dependency><groupid>c3p0</groupid><artifactid>c3p0</artifactid><version> 0.9.1.2</version></dependency>

3.log4.properties

#console loglog4j.appender.console=org.apache.log4j.consoleappenderlog4j.appender.console.layout= Org.apache.log4j.patternlayoutlog4j.appender.console.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%t]%-5p%c -%m%n#all loglog4j.appender.daily_all=org.apache.log4j.dailyrollingfileappenderlog4j.appender.daily_all.layout= org.apache.log4j.patternlayoutlog4j.appender.daily_all.layout.conversionpattern= "%p%d{yyyy-MM-dd HH:mm:ss}%- 50.50C (%l)-%m%nlog4j.appender.daily_all. File=d:/myjaval.loglog4j.appender.daily_all. Datepattern= '. ' yyyy-mm-dd#logger#log4j.logger.org.springframework=info,console#log4j.logger.org.hibernate=info,console# Log4j.logger.org.apache=info,consolelog4j.rootlogger=info,console,daily_all


4.jdbc.properties



jdbc_driverclassname=com.mysql.jdbc.driverjdbc_url=jdbc:mysql://127.0.0.1:3306/test?useunicode=true& Characterencoding=utf8jdbc_username=rootjdbc_password=root

5.applicationcontext.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" Xmlns:tx = "Http://www.springframework.org/schema/tx" xmlns:context= "Http://www.springframework.org/schema/context" xsi: schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/sprin        G-beans.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX http://www.springframework.org/schema/tx/spring-tx.xsd/HTTP    Www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!--declarative transaction Management-<!--introducing external properties Files--<!--<context:property-placeholder location= "Classpath:jdbc.prop Erties "/>-<bean Id= "Propertyconfigurer" class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <            Property Name= "Locations" > <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <!--c3p0 Connection pool--<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > <property name= "driverclass" value= "${jdbc_driverclassname}"/ > <property name= "jdbcurl" value= "${jdbc_url}"/> <property name= "user" value= "${jdbc_username}"/> < Property name= "Password" value= "${jdbc_password}"/> </bean> <!--Configure the business layer--<!--turn on annotation--&L t;context:annotation-config/> <context:component-scan base-package= "Cn.dx.spring.transaction2.service"/ > <context:component-scan base-package= "Cn.dx.spring.transaction2.dao"/><!--jdbc template--><bean id= " JdbcTemplate "class=" Org.springframework.jdbc.core.JdbcTemPlate "><property name=" DataSource "ref=" DataSource "/></bean><!--configuration transaction manager:--><bean id=" TransactionManager "class=" Org.springframework.jdbc.datasource.DataSourceTransactionManager "><property Name= "DataSource" ref= "DataSource"/></bean><!--turn on AOP listening is only valid for the current profile--><aop:aspectj-autoproxy Expose-proxy= "true"/><!--opening the annotation transaction is only valid for the current profile--><tx:annotation-driven transaction-manager= "Txmanager"/ >< Notification of!--configuration transaction--><tx:advice id= "Txadvice" transaction-manager= "TransactionManager" &GT;&LT;TX: attributes><!--Transfre Method (* on behalf of all)--><tx:method name= "Transfer" propagation= "REQUIRED"/&GT;&LT;/TX: attributes></tx:advice><!--To configure the tangency point of a transaction and not associate the transaction pointcut with the transaction properties--><aop:config expose-proxy= "true" > < !--tangency only enforces transactions on the business logic Layer--<aop:pointcut id= "txpointcut" expression= "Execution (* cn.dx.spring. Service: *.*(..))" /> <!--facets--<aop:advisor advice-ref= "Txadvice" pointcut-ref="Txpointcut"/> </aop:config></beans> 


6.DAO and implementation

Package Cn.dx.spring.transaction2.dao;public interface Accountdao {/** * @param out Transfer account * @param money transfer Amount */void Outmon EY (string out,double);/** * @param in: Incoming account * @param money: Transfer amount */void Inmoney (string in,double);}


Package Cn.dx.spring.transaction2.dao.impl;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.jdbc.core.jdbctemplate;import Org.springframework.stereotype.component;import Cn.dx.spring.transaction2.dao.AccountDao, @Component ("Accountdao") public class Accountdaoimpl implements Accountdao {@Autowiredprivate jdbctemplate jdbctemplate; @Overridepublic void Outmoney (string out, Double money) {String sql = "Updat E account Set money = money-? WHERE name =? "; This.jdbcTemplate.update (sql,money,out);} @Overridepublic void Inmoney (string in, Double money) {String sql = ' Update account ' set money = Money +? WHERE name =? "; This.jdbcTemplate.update (Sql,money,in);}}


7.service and implementation

Package cn.dx.spring.transaction2.service;/** * Transfer Service * @author Nobita * */public interface Accountservice {/** *  * @p Aram out: Transfer account * @param in: Transfer account * @param money: Transfer amount */void Transfer (String out,string in,double);}


Package Cn.dx.spring.transaction2.service.impl;import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.beans.factory.annotation.qualifier;import Org.springframework.stereotype.Service; Import Cn.dx.spring.transaction2.dao.accountdao;import Cn.dx.spring.transaction2.service.AccountService; @Service ("Accountservice") public class Accountserviceimpl implements Accountservice {@Autowired @qualifier ("Accountdao") Private Accountdao Accountdao; @Overridepublic void Transfer (final string out,final string in,final Double money) {Account Dao.outmoney (out, money); int i = 1/0;    Accountdao.inmoney (in, Money);}}


8. Testing

Package Cn.dx.myjava.spring.transaction;import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.beans.factory.annotation.qualifier;import Org.springframework.test.context.contextconfiguration;import Org.springframework.test.context.junit4.springjunit4classrunner;import cn.dx.spring.transaction.service.accountservice;/** * Programmatic Transaction Management * Transfer Test * @author Nobita * */@RunWith ( Springjunit4classrunner.class) @ContextConfiguration ("Classpath:applicationContext.xml") public class transtraction {//test Business Layer Class @autowired@qualifier ("Accountservice") private accountservice Accountservice; @Testpublic void  Transaction () {This.accountService.transfer ("AA", "BB", 200d);}}



ASPECTJ Declarative Transaction Configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.