1. 程式人生 > >【例項】使用Spring AOP進行業務增強(通過註解的方式)

【例項】使用Spring AOP進行業務增強(通過註解的方式)

以下程式碼通過了編譯,可以直接執行(需要更改包名)

目的: 通過Spring AOP實現對service的transfer(轉賬)操作增加事務處理。

  • 增強類MyAdvice
package com.bamzhy.advice;

import com.bamzhy.utils.MyC3P0DataSouce;
import com.bamzhy.utils.TransactionManagement;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation
; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import java.sql.Connection; import java.sql.SQLException; @Aspect @Component public class MyAdvice { //設定好增強點 @Pointcut("execution (public boolean com.bamzhy.service.UserServiceImpl.transfer(..)) throws java.sql.SQLException )"
) private void myPointCut(){ } //around方法 @Around("myPointCut()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { Object proceed=null; boolean ret=false; Connection connection=null; try{ connection= MyC3P0DataSouce.getConnection
(); //開啟事務 connection.setAutoCommit(false); //這裡是核心 proceed=joinPoint.proceed(); connection.commit(); connection.close(); ret=true; System.out.println("這裡是增強程式碼"); }catch (Exception e){ e.printStackTrace(); if(connection!=null){ try{ connection.rollback(); }catch (SQLException e1){ e1.printStackTrace(); } } } return proceed; } }
  • 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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--設定掃描的包名-->
    <context:component-scan base-package="com.bamzhy"/>
    <aop:aspectj-autoproxy />
</beans>
  • service層
package com.bamzhy.service;

import com.bamzhy.bean.Account;
import com.bamzhy.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

//service層,例項化時getBean呼叫這個id
@Service("service")
public class UserServiceImpl implements UserService {
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    //自動去UserDao和其子類中(@Repository)尋找例項化物件並注入
    @Autowired
    private UserDao userDao;

    @Override
    public boolean transfer(String usernameFrom, String usernameTo, int money) throws SQLException {
        Account accountFrom = userDao.getAccount(usernameFrom);
        Account accountTo = userDao.getAccount(usernameTo);
        accountFrom.setMoney(accountFrom.getMoney()-money);
        accountTo.setMoney(accountTo.getMoney()+money);
        if (!userDao.updateAccount(accountFrom))
            return false;
        //int i = 1/0;
        if (!userDao.updateAccount(accountTo))
            return false;
        return true;
    }
}
  • dao層
package com.bamzhy.dao;

import com.bamzhy.bean.Account;
import com.bamzhy.utils.TransactionManagement;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;

//Dao層
@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public boolean updateAccount(Account account) throws SQLException {
        QueryRunner queryRunner=new QueryRunner();
        String sql="update homework set money = ? where username = ?;";
        //public int update(Connection conn, String sql, Object... params)
        int update = queryRunner.update(TransactionManagement.getConnection(),sql,account.getMoney(), account.getUsername());
        return update==1?true:false;
    }

    @Override
    public Account getAccount(String username) throws SQLException {
        QueryRunner queryRunner=new QueryRunner();
        String sql="select * from homework where username = ?;";
        Account query = queryRunner.query(TransactionManagement.getConnection(), sql, new BeanHandler<Account>(Account.class), username);
        return query;
    }
}
  • test檔案
package com.bamzhy.test;
import com.bamzhy.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.SQLException;

public class test {
    @Test
    public void test1() throws SQLException {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService service = (UserService) applicationContext.getBean("service");
        service.transfer("haha1","haha2",1000);
    }
}

相關推薦

例項使用Spring AOP進行業務增強通過註解方式

以下程式碼通過了編譯,可以直接執行(需要更改包名) 目的: 通過Spring AOP實現對service的transfer(轉賬)操作增加事務處理。 增強類MyAdvice package

轉載Spring AOP詳解 、 JDK動態代理、CGLib動態代理

rto 工廠 第一個 lec 僅支持 sel clas sleep gpo 原文地址:https://www.cnblogs.com/kukudelaomao/p/5897893.html AOP是Aspect Oriented Programing的簡稱,面向切面

Java Spring 框架初步學習總結簡單實現 IoC 和 AOP

1.0 其中 表示 只需要 第一篇 否則 info fin pojo   Spring 是一個開源的設計層面的輕量級框架,Spring 的好處網上有太多,這裏就不在贅述。   IoC 控制反轉和 AOP 面向切面編程是 Spring 的兩個重要特性。   IoC(Inver

框架[Spring]AOP攔截-三種方式實現自動代理

這裡的自動代理,我講的是自動代理bean物件,其實就是在xml中讓我們不用配置代理工廠,也就是不用配置class為org.springframework.aop.framework.ProxyFactoryBean的bean。 總結了一下自己目前所學的知識

轉載Spring AOP

6.3.7. 例子 讓我們來看看在 Section 6.2.7, “例子” 提過併發鎖失敗重試的例子,如果使用schema對這個例子進行重寫是什麼效果。 因為併發鎖的關係,有時候business services可能會失敗(例如,死鎖失敗)。 如果重新嘗試一下,很有可能就會

知識庫--spring aop 動態代理--inner private protected 方法失效212

私有方法或者保護的方法無效! AspectJ pointcut for annotated PRIVATE methods Due to the proxy-based nature of Spring's AOP framework, protected methods

原創Spring-AOP代理類繼承介面..

Computer.java  package org.rockie; public class Computer implements PcInterf{ private String pcName="rockie007"; private int pcPrice=5000;

轉載spring boot 連結 虛擬機器Linux redis

原文:https://www.imooc.com/article/43279?block_id=tuijian_wz 前提是你已經安裝redis且支援遠端連線,redis的安裝這裡不再贅述,有需要的可以參考我的另一篇文章:centos 7.3上安裝redis。這裡主要講講如何判斷及設定redis支援遠端連線

Selenium使用selenium進行自動化測試

1.元素定位與操作 查詢元素方法: driver.findElement(By arg0); 其中寫用來定位的API,常見用來定位的API有六種,接下來一一介紹: 1.1 By.id 根據id來獲取元素,返回單個元素,因為id值一般是唯一的。 //獲得id

spring cloud 入門負載均衡與 FeignClient 容錯機制一通過類容錯

一 負載均衡 spring cloud 負載均衡非常簡單,現在服務提供者 menu,重新copy 一份munu ,命名 menu2 ,將埠 修改為 8764 ,其他配置都不變 這個時候 如何 再次呼叫 user/getMenu 介面, 檢視 menu 和 menu2 的日誌,我們可以看出來,

Spring Bean的生命週期非常詳細

Spring作為當前Java最流行、最強大的輕量級框架,受到了程式設計師的熱烈歡迎。準確的瞭解Spring Bean的生命週期是非常必要的。我們通常使用ApplicationContext作為Spring容器。這裡,我們講的也是 ApplicationContext中Be

QuartzQuartz的搭建、應用單獨使用Quartz

文章 sgd aca guide mfc uci strong div guid 原文:http://www.cnblogs.com/nick-huang/p/4848843.html 目錄 1. > 參考的優秀資料 2. > 版本說明 3. > 簡單的

Appium的安裝-Mac平臺命令行 dmg

兼容性問題 壓縮 解壓 3.1 修改文件 9.png 根據 ref 成功 其實Appium的安裝方式主要有兩種: 1)自己安裝配置nodejs的環境,然後通過npm進行appium的安裝 2)直接下載官網提供的dmg進行安裝,dmg裏面已經有

BZOJ4524[Cqoi2016]偽光滑數 堆模擬搜索

整數 多少 while i++ size pop truct 滿足 答案 【BZOJ4524】[Cqoi2016]偽光滑數 Description 若一個大於1的整數M的質因數分解有k項,其最大的質因子為Ak,並且滿足Ak^K<=N,Ak<128,我們就

總結遊戲框架與架構設計Unity為例

單機 業務 github 事件 概念 lec 集合 架構模式 wid 使用框架開發遊戲 優點:耦合性低,重用性高,部署快,可維護性高,方便管理。提高開發效率,降低開發難度 缺點:增加了系統結構和實現的復雜性,需要額外花費精力維護,不適合小型程序,易影響運行效率 常見

整理常用電子設備功耗不定期更新

沒事 標準 優酷 運行 充電 電子 組裝 由器 1.2 NAS 關機:1.4W(我擦,關機還耗電,還不少) 待機:20W 運行:20W+每塊3.5寸硬盤5W PC 關機:1.2W 待機:45W(要不是你太吵,那你當nas也可以) 處理器滿負荷:100W 顯卡滿負荷:180

mysql反引號的使用防沖突

rev delete 僅供參考 cte each 必須 repl exc 沖突 轉載地址:http://blog.itechol.com/space.php?uid=33&do=blog&id=6681 1、mysql語句中 反引號 【`】作用: 避免表明

節選--揭祕命名函式表示式Named function expressions

作者:Juriy "kangax" Zaytsev 原文連結:kangax.github.io/nfe/ 簡介 令人驚訝的是,在網上,關於命名函式表示式的討論似乎並不多。這可能因為有很多誤解在流傳。在本文中,我會試著從理論和實踐兩個方面總結這些精彩的Javascript構念,包括其中好的

題解洛谷P1273 有線電視網樹上分組揹包

次元傳送門:洛谷P1273 思路 一開始想的是普通樹形DP 但是好像實現不大好 觀摩了一下題解 是樹上分組揹包 設f[i][j]為以i為根的子樹中取j個客戶得到的總價值 我們可以以i為根有j組 在每一組中分別又取1個,2個,3個......n個客戶 化為揹包思想即 j為一共有j組 揹包容量為每

PHP判斷客戶執行的環境pc與手機

class self_test { const PC = 'pc'; const SP = 'sp'; private $_splist = array('iPhone','Android','iPod','iPad','Tizen');//設定經常使用的sp終端