日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

基于注解的AOP实现事务控制及问题分析

發布時間:2024/4/13 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 基于注解的AOP实现事务控制及问题分析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.learn</groupId><artifactId>\day04_learn_03account_aoptx_anno</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>commons-dbutils</groupId><artifactId>commons-dbutils</artifactId><version>1.4</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.45</version></dependency><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1.2</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.7</version></dependency></dependencies></project> package com.learn.dao.impl;import com.learn.dao.IAccountDao; import com.learn.domain.Account; import com.learn.utils.ConnectionUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;import java.util.List;/*** 賬戶的持久層實現類*/ @Repository("accountDao") public class AccountDaoImpl implements IAccountDao {@Autowiredprivate QueryRunner runner;@Autowiredprivate ConnectionUtils connectionUtils;public List<Account> findAllAccount() {try{return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));}catch (Exception e) {throw new RuntimeException(e);}}public Account findAccountById(Integer accountId) {try{return runner.query(connectionUtils.getThreadConnection(),"select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);}catch (Exception e) {throw new RuntimeException(e);}}public void saveAccount(Account account) {try{runner.update(connectionUtils.getThreadConnection(),"insert into account(name,money)values(?,?)",account.getName(),account.getMoney());}catch (Exception e) {throw new RuntimeException(e);}}public void updateAccount(Account account) {try{runner.update(connectionUtils.getThreadConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());}catch (Exception e) {throw new RuntimeException(e);}}public void deleteAccount(Integer accountId) {try{runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",accountId);}catch (Exception e) {throw new RuntimeException(e);}}public Account findAccountByName(String accountName) {try{List<Account> accounts = runner.query(connectionUtils.getThreadConnection(),"select * from account where name = ? ",new BeanListHandler<Account>(Account.class),accountName);if(accounts == null || accounts.size() == 0){return null;}if(accounts.size() > 1){throw new RuntimeException("結果集不唯一,數據有問題");}return accounts.get(0);}catch (Exception e) {throw new RuntimeException(e);}} } package com.learn.dao;import com.learn.domain.Account;import java.util.List;/*** 賬戶的持久層接口*/ public interface IAccountDao {/*** 查詢所有* @return*/List<Account> findAllAccount();/*** 查詢一個* @return*/Account findAccountById(Integer accountId);/*** 保存* @param account*/void saveAccount(Account account);/*** 更新* @param account*/void updateAccount(Account account);/*** 刪除* @param acccountId*/void deleteAccount(Integer acccountId);/*** 根據名稱查詢賬戶* @param accountName* @return 如果有唯一的一個結果就返回,如果沒有結果就返回null* 如果結果集超過一個就拋異常*/Account findAccountByName(String accountName); } package com.learn.domain;import java.io.Serializable;/*** 賬戶的實體類*/ public class Account implements Serializable {private Integer id;private String name;private Float money;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Float getMoney() {return money;}public void setMoney(Float money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';} } package com.learn.service;import com.learn.domain.Account;import java.util.List;/*** 賬戶的業務層接口*/ public interface IAccountService {/*** 查詢所有* @return*/List<Account> findAllAccount();/*** 查詢一個* @return*/Account findAccountById(Integer accountId);/*** 保存* @param account*/void saveAccount(Account account);/*** 更新* @param account*/void updateAccount(Account account);/*** 刪除* @param acccountId*/void deleteAccount(Integer acccountId);/*** 轉賬* @param sourceName 轉出賬戶名稱* @param targetName 轉入賬戶名稱* @param money 轉賬金額*/void transfer(String sourceName, String targetName, Float money);//void test();//它只是連接點,但不是切入點,因為沒有被增強 } package com.learn.utils;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;import javax.sql.DataSource; import java.sql.Connection;/*** 連接的工具類,它用于從數據源中獲取一個連接,并且實現和線程的綁定*/ @Component("connectionUtils") public class ConnectionUtils {private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();@Autowiredprivate DataSource dataSource;/*** 獲取當前線程上的連接* @return*/public Connection getThreadConnection() {try{//1.先從ThreadLocal上獲取Connection conn = tl.get();//2.判斷當前線程上是否有連接if (conn == null) {//3.從數據源中獲取一個連接,并且存入ThreadLocal中conn = dataSource.getConnection();tl.set(conn);}//4.返回當前線程上的連接return conn;}catch (Exception e){throw new RuntimeException(e);}}/*** 把連接和線程解綁*/public void removeConnection(){tl.remove();} } package com.learn.utils;import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;/*** 和事務管理相關的工具類,它包含了,開啟事務,提交事務,回滾事務和釋放連接*/ @Component("txManager") @Aspect public class TransactionManager {@Autowiredprivate ConnectionUtils connectionUtils;@Pointcut("execution(* com.learn.service.impl.*.*(..))")private void pt1(){}/*** 開啟事務*/public void beginTransaction(){try {connectionUtils.getThreadConnection().setAutoCommit(false);}catch (Exception e){e.printStackTrace();}}/*** 提交事務*/public void commit(){try {connectionUtils.getThreadConnection().commit();}catch (Exception e){e.printStackTrace();}}/*** 回滾事務*/public void rollback(){try {connectionUtils.getThreadConnection().rollback();}catch (Exception e){e.printStackTrace();}}/*** 釋放連接*/public void release(){try {connectionUtils.getThreadConnection().close();//還回連接池中connectionUtils.removeConnection();}catch (Exception e){e.printStackTrace();}}@Around("pt1()")public Object aroundAdvice(ProceedingJoinPoint pjp){Object rtValue = null;try {//1.獲取參數Object[] args = pjp.getArgs();//2.開啟事務this.beginTransaction();//3.執行方法rtValue = pjp.proceed(args);//4.提交事務this.commit();//返回結果return rtValue;}catch (Throwable e){//5.回滾事務this.rollback();throw new RuntimeException(e);}finally {//6.釋放資源this.release();}} } package com.learn.service.impl;import com.learn.dao.IAccountDao; import com.learn.domain.Account; import com.learn.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import java.util.List;/*** 賬戶的業務層實現類** 事務控制應該都是在業務層*/ @Service("accountService") public class AccountServiceImpl implements IAccountService{@Autowiredprivate IAccountDao accountDao;public List<Account> findAllAccount() {return accountDao.findAllAccount();}public Account findAccountById(Integer accountId) {return accountDao.findAccountById(accountId);}public void saveAccount(Account account) {accountDao.saveAccount(account);}public void updateAccount(Account account) {accountDao.updateAccount(account);}public void deleteAccount(Integer acccountId) {accountDao.deleteAccount(acccountId);}public void transfer(String sourceName, String targetName, Float money) {System.out.println("transfer....");//2.1根據名稱查詢轉出賬戶Account source = accountDao.findAccountByName(sourceName);//2.2根據名稱查詢轉入賬戶Account target = accountDao.findAccountByName(targetName);//2.3轉出賬戶減錢source.setMoney(source.getMoney()-money);//2.4轉入賬戶加錢target.setMoney(target.getMoney()+money);//2.5更新轉出賬戶accountDao.updateAccount(source);// int i=1/0;//2.6更新轉入賬戶accountDao.updateAccount(target);} } <?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:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--配置spring創建容器時要掃描的包--><context:component-scan base-package="com.learn"></context:component-scan><!--配置QueryRunner--><bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"></bean><!-- 配置數據源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><!--連接數據庫的必備信息--><property name="driverClass" value="com.mysql.jdbc.Driver"></property><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property><property name="user" value="root"></property><property name="password" value="123456"></property></bean><!--開啟spring對注解AOP的支持--><aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans> package com.learn.test;import com.learn.service.IAccountService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/*** 使用Junit單元測試:測試我們的配置*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:bean.xml") public class AccountServiceTest {@Autowiredprivate IAccountService as;@Testpublic void testTransfer(){as.transfer("aaa","bbb",100f);}}

?

總結

以上是生活随笔為你收集整理的基于注解的AOP实现事务控制及问题分析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。