主頁 > 資料庫 > 手寫IOC及AOP

手寫IOC及AOP

2021-06-16 18:48:16 資料庫

手寫ioc&aop

  • 1.概念
    • IOC:Inversion of control 控制反轉
    • AOP:Aspect oriented Programming 面向切面編程
  • 2.通過銀行轉賬案例手寫IOC和AOP
    • 2.1.表結構
    • 2.2.銀行轉賬呼叫關系
    • 2.3.分析存在的問題
    • 2.4.解決問題思路
    • 2.5.通過IOC及AOP進行改造
      • 2.5.0.pom.xml
      • 2.5.1.index.xml
      • 2.5.2.beans.xml
      • 2.5.3.工具類
      • 2.5.4.pojo
      • 2.5.5.工廠類
      • 2.5.6.dao層
      • 2.5.7.service層
      • 2.5.8.controller層
      • 2.5.9.注意事項

1.概念

IOC:Inversion of control 控制反轉

  • 控制:指的是物件創建(實體化、管理)的權利
  • 反轉:控制權交給外部環境了(spring框架、IoC容器)
  • 傳統開發?式:?如類A依賴于類B,往往會在類A中new?個B的物件
  • IoC思想下開發方式:我們不???去new物件了,?是由IoC容器(Spring框架)去幫助我們實體化物件并且管理它,我們需要使?哪個物件,去問IoC容器要即可,
  • 解決的問題:解決物件之間的耦合問題,避免new關鍵字
  • Ioc和DI區別:IOC和DI是從不同角度描述同一件事情(物件實體化及依賴關系維護這件事情),IOC是站在物件的角度,物件實體化及其管理的權力交給了(反轉)容器,DI:Dependancy Injection(依賴注?),是站在容器的角度,容器會把物件依賴的其他物件注入(送進去),比如A物件實體化程序中因為宣告了一個B型別的屬性,那么就需要容器把B物件注入給A

AOP:Aspect oriented Programming 面向切面編程

  • 起源:aop是oop的延續,oop三大特征:封裝、繼承、多型,是一種垂直縱向的繼承體系,OOP編程思想可以解決?多數的代碼重復問題,但是有?些情況是處理不了的,?如在頂級?類中的多個?法中相同位置出現了重復代碼,OOP就解決不了
  • 橫切邏輯代碼問題:1.橫切代碼重復問題,2.橫切邏輯代碼和業務代碼混雜在?起,代碼臃腫,維護不?便
  • AOP解決的問題:在不改變原有業務邏輯情況下,增強橫切邏輯代碼,根本上解耦合,避免橫切邏輯代碼重復
  • 面向切面編程理解:「切」:指的是橫切邏輯,原有業務邏輯代碼我們不能動,只能操作橫切邏輯代碼,所以?向橫切邏輯,「?」:橫切邏輯代碼往往要影響的是很多個?法,每?個?法都如同?個點,多個點構成?,有?個?的概念在??

2.通過銀行轉賬案例手寫IOC和AOP

2.1.表結構

CREATE TABLE `account` (
  `name` varchar(255) DEFAULT NULL COMMENT '用戶名',
  `money` varchar(255) DEFAULT NULL COMMENT '賬戶金額',
  `cardNo` varchar(255) NOT NULL COMMENT '銀行卡號'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.2.銀行轉賬呼叫關系

<style>#mermaid-svg-gsEuPTWdGtRPZL5X .label{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);fill:#333;color:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .label text{fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .node rect,#mermaid-svg-gsEuPTWdGtRPZL5X .node circle,#mermaid-svg-gsEuPTWdGtRPZL5X .node ellipse,#mermaid-svg-gsEuPTWdGtRPZL5X .node polygon,#mermaid-svg-gsEuPTWdGtRPZL5X .node path{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-gsEuPTWdGtRPZL5X .node .label{text-align:center;fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .node.clickable{cursor:pointer}#mermaid-svg-gsEuPTWdGtRPZL5X .arrowheadPath{fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .edgePath .path{stroke:#333;stroke-width:1.5px}#mermaid-svg-gsEuPTWdGtRPZL5X .flowchart-link{stroke:#333;fill:none}#mermaid-svg-gsEuPTWdGtRPZL5X .edgeLabel{background-color:#e8e8e8;text-align:center}#mermaid-svg-gsEuPTWdGtRPZL5X .edgeLabel rect{opacity:0.9}#mermaid-svg-gsEuPTWdGtRPZL5X .edgeLabel span{color:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .cluster rect{fill:#ffffde;stroke:#aa3;stroke-width:1px}#mermaid-svg-gsEuPTWdGtRPZL5X .cluster text{fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:12px;background:#ffffde;border:1px solid #aa3;border-radius:2px;pointer-events:none;z-index:100}#mermaid-svg-gsEuPTWdGtRPZL5X .actor{stroke:#ccf;fill:#ECECFF}#mermaid-svg-gsEuPTWdGtRPZL5X text.actor>tspan{fill:#000;stroke:none}#mermaid-svg-gsEuPTWdGtRPZL5X .actor-line{stroke:grey}#mermaid-svg-gsEuPTWdGtRPZL5X .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .messageLine1{stroke-width:1.5;stroke-dasharray:2, 2;stroke:#333}#mermaid-svg-gsEuPTWdGtRPZL5X #arrowhead path{fill:#333;stroke:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .sequenceNumber{fill:#fff}#mermaid-svg-gsEuPTWdGtRPZL5X #sequencenumber{fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X #crosshead path{fill:#333;stroke:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .messageText{fill:#333;stroke:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .labelBox{stroke:#ccf;fill:#ECECFF}#mermaid-svg-gsEuPTWdGtRPZL5X .labelText,#mermaid-svg-gsEuPTWdGtRPZL5X .labelText>tspan{fill:#000;stroke:none}#mermaid-svg-gsEuPTWdGtRPZL5X .loopText,#mermaid-svg-gsEuPTWdGtRPZL5X .loopText>tspan{fill:#000;stroke:none}#mermaid-svg-gsEuPTWdGtRPZL5X .loopLine{stroke-width:2px;stroke-dasharray:2, 2;stroke:#ccf;fill:#ccf}#mermaid-svg-gsEuPTWdGtRPZL5X .note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-gsEuPTWdGtRPZL5X .noteText,#mermaid-svg-gsEuPTWdGtRPZL5X .noteText>tspan{fill:#000;stroke:none}#mermaid-svg-gsEuPTWdGtRPZL5X .activation0{fill:#f4f4f4;stroke:#666}#mermaid-svg-gsEuPTWdGtRPZL5X .activation1{fill:#f4f4f4;stroke:#666}#mermaid-svg-gsEuPTWdGtRPZL5X .activation2{fill:#f4f4f4;stroke:#666}#mermaid-svg-gsEuPTWdGtRPZL5X .mermaid-main-font{font-family:"trebuchet ms", verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-gsEuPTWdGtRPZL5X .section{stroke:none;opacity:0.2}#mermaid-svg-gsEuPTWdGtRPZL5X .section0{fill:rgba(102,102,255,0.49)}#mermaid-svg-gsEuPTWdGtRPZL5X .section2{fill:#fff400}#mermaid-svg-gsEuPTWdGtRPZL5X .section1,#mermaid-svg-gsEuPTWdGtRPZL5X .section3{fill:#fff;opacity:0.2}#mermaid-svg-gsEuPTWdGtRPZL5X .sectionTitle0{fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .sectionTitle1{fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .sectionTitle2{fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .sectionTitle3{fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .sectionTitle{text-anchor:start;font-size:11px;text-height:14px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-gsEuPTWdGtRPZL5X .grid .tick{stroke:#d3d3d3;opacity:0.8;shape-rendering:crispEdges}#mermaid-svg-gsEuPTWdGtRPZL5X .grid .tick text{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-gsEuPTWdGtRPZL5X .grid path{stroke-width:0}#mermaid-svg-gsEuPTWdGtRPZL5X .today{fill:none;stroke:red;stroke-width:2px}#mermaid-svg-gsEuPTWdGtRPZL5X .task{stroke-width:2}#mermaid-svg-gsEuPTWdGtRPZL5X .taskText{text-anchor:middle;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-gsEuPTWdGtRPZL5X .taskText:not([font-size]){font-size:11px}#mermaid-svg-gsEuPTWdGtRPZL5X .taskTextOutsideRight{fill:#000;text-anchor:start;font-size:11px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-gsEuPTWdGtRPZL5X .taskTextOutsideLeft{fill:#000;text-anchor:end;font-size:11px}#mermaid-svg-gsEuPTWdGtRPZL5X .task.clickable{cursor:pointer}#mermaid-svg-gsEuPTWdGtRPZL5X .taskText.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-gsEuPTWdGtRPZL5X .taskTextOutsideLeft.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-gsEuPTWdGtRPZL5X .taskTextOutsideRight.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-gsEuPTWdGtRPZL5X .taskText0,#mermaid-svg-gsEuPTWdGtRPZL5X .taskText1,#mermaid-svg-gsEuPTWdGtRPZL5X .taskText2,#mermaid-svg-gsEuPTWdGtRPZL5X .taskText3{fill:#fff}#mermaid-svg-gsEuPTWdGtRPZL5X .task0,#mermaid-svg-gsEuPTWdGtRPZL5X .task1,#mermaid-svg-gsEuPTWdGtRPZL5X .task2,#mermaid-svg-gsEuPTWdGtRPZL5X .task3{fill:#8a90dd;stroke:#534fbc}#mermaid-svg-gsEuPTWdGtRPZL5X .taskTextOutside0,#mermaid-svg-gsEuPTWdGtRPZL5X .taskTextOutside2{fill:#000}#mermaid-svg-gsEuPTWdGtRPZL5X .taskTextOutside1,#mermaid-svg-gsEuPTWdGtRPZL5X .taskTextOutside3{fill:#000}#mermaid-svg-gsEuPTWdGtRPZL5X .active0,#mermaid-svg-gsEuPTWdGtRPZL5X .active1,#mermaid-svg-gsEuPTWdGtRPZL5X .active2,#mermaid-svg-gsEuPTWdGtRPZL5X .active3{fill:#bfc7ff;stroke:#534fbc}#mermaid-svg-gsEuPTWdGtRPZL5X .activeText0,#mermaid-svg-gsEuPTWdGtRPZL5X .activeText1,#mermaid-svg-gsEuPTWdGtRPZL5X .activeText2,#mermaid-svg-gsEuPTWdGtRPZL5X .activeText3{fill:#000 !important}#mermaid-svg-gsEuPTWdGtRPZL5X .done0,#mermaid-svg-gsEuPTWdGtRPZL5X .done1,#mermaid-svg-gsEuPTWdGtRPZL5X .done2,#mermaid-svg-gsEuPTWdGtRPZL5X .done3{stroke:grey;fill:#d3d3d3;stroke-width:2}#mermaid-svg-gsEuPTWdGtRPZL5X .doneText0,#mermaid-svg-gsEuPTWdGtRPZL5X .doneText1,#mermaid-svg-gsEuPTWdGtRPZL5X .doneText2,#mermaid-svg-gsEuPTWdGtRPZL5X .doneText3{fill:#000 !important}#mermaid-svg-gsEuPTWdGtRPZL5X .crit0,#mermaid-svg-gsEuPTWdGtRPZL5X .crit1,#mermaid-svg-gsEuPTWdGtRPZL5X .crit2,#mermaid-svg-gsEuPTWdGtRPZL5X .crit3{stroke:#f88;fill:red;stroke-width:2}#mermaid-svg-gsEuPTWdGtRPZL5X .activeCrit0,#mermaid-svg-gsEuPTWdGtRPZL5X .activeCrit1,#mermaid-svg-gsEuPTWdGtRPZL5X .activeCrit2,#mermaid-svg-gsEuPTWdGtRPZL5X .activeCrit3{stroke:#f88;fill:#bfc7ff;stroke-width:2}#mermaid-svg-gsEuPTWdGtRPZL5X .doneCrit0,#mermaid-svg-gsEuPTWdGtRPZL5X .doneCrit1,#mermaid-svg-gsEuPTWdGtRPZL5X .doneCrit2,#mermaid-svg-gsEuPTWdGtRPZL5X .doneCrit3{stroke:#f88;fill:#d3d3d3;stroke-width:2;cursor:pointer;shape-rendering:crispEdges}#mermaid-svg-gsEuPTWdGtRPZL5X .milestone{transform:rotate(45deg) scale(0.8, 0.8)}#mermaid-svg-gsEuPTWdGtRPZL5X .milestoneText{font-style:italic}#mermaid-svg-gsEuPTWdGtRPZL5X .doneCritText0,#mermaid-svg-gsEuPTWdGtRPZL5X .doneCritText1,#mermaid-svg-gsEuPTWdGtRPZL5X .doneCritText2,#mermaid-svg-gsEuPTWdGtRPZL5X .doneCritText3{fill:#000 !important}#mermaid-svg-gsEuPTWdGtRPZL5X .activeCritText0,#mermaid-svg-gsEuPTWdGtRPZL5X .activeCritText1,#mermaid-svg-gsEuPTWdGtRPZL5X .activeCritText2,#mermaid-svg-gsEuPTWdGtRPZL5X .activeCritText3{fill:#000 !important}#mermaid-svg-gsEuPTWdGtRPZL5X .titleText{text-anchor:middle;font-size:18px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-gsEuPTWdGtRPZL5X g.classGroup text{fill:#9370db;stroke:none;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:10px}#mermaid-svg-gsEuPTWdGtRPZL5X g.classGroup text .title{font-weight:bolder}#mermaid-svg-gsEuPTWdGtRPZL5X g.clickable{cursor:pointer}#mermaid-svg-gsEuPTWdGtRPZL5X g.classGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-gsEuPTWdGtRPZL5X g.classGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-gsEuPTWdGtRPZL5X .classLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5}#mermaid-svg-gsEuPTWdGtRPZL5X .classLabel .label{fill:#9370db;font-size:10px}#mermaid-svg-gsEuPTWdGtRPZL5X .relation{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-gsEuPTWdGtRPZL5X .dashed-line{stroke-dasharray:3}#mermaid-svg-gsEuPTWdGtRPZL5X #compositionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-gsEuPTWdGtRPZL5X #compositionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-gsEuPTWdGtRPZL5X #aggregationStart{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-gsEuPTWdGtRPZL5X #aggregationEnd{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-gsEuPTWdGtRPZL5X #dependencyStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-gsEuPTWdGtRPZL5X #dependencyEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-gsEuPTWdGtRPZL5X #extensionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-gsEuPTWdGtRPZL5X #extensionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-gsEuPTWdGtRPZL5X .commit-id,#mermaid-svg-gsEuPTWdGtRPZL5X .commit-msg,#mermaid-svg-gsEuPTWdGtRPZL5X .branch-label{fill:lightgrey;color:lightgrey;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-gsEuPTWdGtRPZL5X .pieTitleText{text-anchor:middle;font-size:25px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-gsEuPTWdGtRPZL5X .slice{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-gsEuPTWdGtRPZL5X g.stateGroup text{fill:#9370db;stroke:none;font-size:10px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-gsEuPTWdGtRPZL5X g.stateGroup text{fill:#9370db;fill:#333;stroke:none;font-size:10px}#mermaid-svg-gsEuPTWdGtRPZL5X g.statediagram-cluster .cluster-label text{fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X g.stateGroup .state-title{font-weight:bolder;fill:#000}#mermaid-svg-gsEuPTWdGtRPZL5X g.stateGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-gsEuPTWdGtRPZL5X g.stateGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-gsEuPTWdGtRPZL5X .transition{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-gsEuPTWdGtRPZL5X .stateGroup .composit{fill:white;border-bottom:1px}#mermaid-svg-gsEuPTWdGtRPZL5X .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px}#mermaid-svg-gsEuPTWdGtRPZL5X .state-note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-gsEuPTWdGtRPZL5X .state-note text{fill:black;stroke:none;font-size:10px}#mermaid-svg-gsEuPTWdGtRPZL5X .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.7}#mermaid-svg-gsEuPTWdGtRPZL5X .edgeLabel text{fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .stateLabel text{fill:#000;font-size:10px;font-weight:bold;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-gsEuPTWdGtRPZL5X .node circle.state-start{fill:black;stroke:black}#mermaid-svg-gsEuPTWdGtRPZL5X .node circle.state-end{fill:black;stroke:white;stroke-width:1.5}#mermaid-svg-gsEuPTWdGtRPZL5X #statediagram-barbEnd{fill:#9370db}#mermaid-svg-gsEuPTWdGtRPZL5X .statediagram-cluster rect{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-gsEuPTWdGtRPZL5X .statediagram-cluster rect.outer{rx:5px;ry:5px}#mermaid-svg-gsEuPTWdGtRPZL5X .statediagram-state .divider{stroke:#9370db}#mermaid-svg-gsEuPTWdGtRPZL5X .statediagram-state .title-state{rx:5px;ry:5px}#mermaid-svg-gsEuPTWdGtRPZL5X .statediagram-cluster.statediagram-cluster .inner{fill:white}#mermaid-svg-gsEuPTWdGtRPZL5X .statediagram-cluster.statediagram-cluster-alt .inner{fill:#e0e0e0}#mermaid-svg-gsEuPTWdGtRPZL5X .statediagram-cluster .inner{rx:0;ry:0}#mermaid-svg-gsEuPTWdGtRPZL5X .statediagram-state rect.basic{rx:5px;ry:5px}#mermaid-svg-gsEuPTWdGtRPZL5X .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#efefef}#mermaid-svg-gsEuPTWdGtRPZL5X .note-edge{stroke-dasharray:5}#mermaid-svg-gsEuPTWdGtRPZL5X .statediagram-note rect{fill:#fff5ad;stroke:#aa3;stroke-width:1px;rx:0;ry:0}:root{--mermaid-font-family: '"trebuchet ms", verdana, arial';--mermaid-font-family: "Comic Sans MS", "Comic Sans", cursive}#mermaid-svg-gsEuPTWdGtRPZL5X .error-icon{fill:#522}#mermaid-svg-gsEuPTWdGtRPZL5X .error-text{fill:#522;stroke:#522}#mermaid-svg-gsEuPTWdGtRPZL5X .edge-thickness-normal{stroke-width:2px}#mermaid-svg-gsEuPTWdGtRPZL5X .edge-thickness-thick{stroke-width:3.5px}#mermaid-svg-gsEuPTWdGtRPZL5X .edge-pattern-solid{stroke-dasharray:0}#mermaid-svg-gsEuPTWdGtRPZL5X .edge-pattern-dashed{stroke-dasharray:3}#mermaid-svg-gsEuPTWdGtRPZL5X .edge-pattern-dotted{stroke-dasharray:2}#mermaid-svg-gsEuPTWdGtRPZL5X .marker{fill:#333}#mermaid-svg-gsEuPTWdGtRPZL5X .marker.cross{stroke:#333} :root { --mermaid-font-family: "trebuchet ms", verdana, arial;}</style> <style>#mermaid-svg-gsEuPTWdGtRPZL5X { color: rgba(0, 0, 0, 0.75); font: ; }</style> 轉賬頁面 TransferServlet TransferService AccountDao JdbcAccountDaoImpl MybatisAccountDaoImpl 點擊'轉出',頁面發起ajax,請求到TransferServlet TransferServlet中實體化service層物件,并呼叫service層方法- TransferService transferService = new TransferServiceImpl() TransferService中實體化dao層物件,并呼叫dao層方- AccountDao dao=new JdbcAccountDaoImpl() Dao層實作原生JDBC 如果要切換成Mybatis實作呢? 轉賬頁面 TransferServlet TransferService AccountDao JdbcAccountDaoImpl MybatisAccountDaoImpl

2.3.分析存在的問題

  • (1)問題?:在上述案例實作中,service 層實作類在使? dao 層物件時,直接在TransferServiceImpl 中通過 AccountDao accountDao = new JdbcAccountDaoImpl() 獲得了 dao層物件,然??個 new 關鍵字卻將 TransferServiceImpl 和 dao 層具體的?個實作類JdbcAccountDaoImpl 耦合在了?起,如果說技術架構發??些變動,dao 層的實作要使?其它技術,?如 Mybatis,思考切換起來的成本?每?個 new 的地?都需要修改源代碼,重新編譯,?向接?開發的意義將?打折扣?
  • (2)問題?:service 層代碼沒有竟然還沒有進?事務控制 ?!如果轉賬程序中出現例外,將可能導致資料庫資料錯亂,后果可能會很嚴重,尤其在?融業務

2.4.解決問題思路

  • 實體化物件的?式除了 new 之外,還有什么技術?反射 (需要把類的全限定類名配置在xml中)
  • 考慮使?設計模式中的??模式解耦合,另外項?中往往有很多物件需要實體化,那就在??中使?反 射技術實體化物件,??模式很合適
  • service 層沒有添加事務控制,怎么辦?沒有事務就添加上事務控制,?動控制 JDBC 的Connection 事務,但要注意將Connection和當前執行緒系結(即保證?個執行緒只有?個Connection,這樣操作才針對的是同?個 Connection,進?控制的是同?個事務),分析:資料庫的事務歸根結底是Connection的事務connection.commit();提交事務 connection.rollback();回滾事務

2.5.通過IOC及AOP進行改造

2.5.0.pom.xml

<?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.lagou.edu</groupId>
  <artifactId>lagou-transfer</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>lagou-transfer Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>


  <dependencies>
    <!-- 單元測驗Junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <!-- mysql資料庫驅動包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.35</version>
    </dependency>
    <!--druid連接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.21</version>
    </dependency>

    <!-- servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- jackson依賴 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.6</version>
    </dependency>

    <!--dom4j依賴-->
    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.6.1</version>
    </dependency>
    <!--xpath運算式依賴-->
    <dependency>
      <groupId>jaxen</groupId>
      <artifactId>jaxen</artifactId>
      <version>1.1.6</version>
    </dependency>
    <!--引入cglib依賴包-->
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>2.1_2</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <!-- 配置Maven的JDK編譯級別 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <configuration>
          <source>11</source>
          <target>11</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>

      <!-- tomcat7插件 -->
      <!-- 注意:目前來說,maven中央倉庫還沒有tomcat8的插件 -->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <port>8080</port>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

2.5.1.index.xml

<!doctype html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>轉賬匯款</title>

    <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>


    <style type="text/css">
        body {
            background-color:#00b38a;
            text-align:center;
        }

        .lp-login {
            position:absolute;
            width:500px;
            height:300px;
            top:50%;
            left:50%;
            margin-top:-250px;
            margin-left:-250px;
            background: #ffffff;
            border-radius: 4px;
            box-shadow: 0 0 10px #12a591;
            padding: 57px 50px 35px;
            box-sizing: border-box
        }


        .lp-login .submitBtn {
            display:block;
            text-decoration:none;
            height: 48px;
            width: 150px;
            line-height: 48px;
            font-size: 16px;
            color: #fff;
            text-align: center;
            background-image: -webkit-gradient(linear, left top, right top, from(#09cb9d), to(#02b389));
            background-image: linear-gradient(90deg, #09cb9d, #02b389);
            border-radius: 3px
        }


        input[type='text'] {
            height:30px;
            width:250px;
        }

        span {
            font-style: normal;
            font-variant-ligatures: normal;
            font-variant-caps: normal;
            font-variant-numeric: normal;
            font-variant-east-asian: normal;
            font-weight: normal;
            font-stretch: normal;
            font-size: 14px;
            line-height: 22px;
            font-family: "Hiragino Sans GB", "Microsoft Yahei", SimSun, Arial, "Helvetica Neue", Helvetica;
        }

    </style>
    <script type="text/javascript">
        $(function(){
            $(".submitBtn").bind("click",function(){
                var fromAccount = $("#fromAccount").val();
                var toAccount = $("#toAccount").val();
                var money = $("#money").val();

                if(money == null || $.trim(money).length == 0){
                    alert("sorry,必須輸入轉賬金額~");
                    return;
                }

                $.ajax({
                    url:'/transferServlet',
                    type:'POST',    //GET
                    async:false,    //或false,是否異步
                    data:{
                        fromCardNo:fromAccount.split(' ')[1],
                        toCardNo:toAccount.split(' ')[1],
                        money:money
                    },
                    timeout:5000,    //超時時間
                    dataType:'json', //回傳的資料格式:json/xml/html/script/jsonp/text
                    success:function(data){
                        if("200" == data.status){
                            alert("轉賬成功~~~");
                        }else{
                            alert("轉賬失敗~~~,message:" + data.message);
                        }
                    }
                })
            })
        })

        //檢查輸入值是否為整數
        function checkFormat(obj){
            var reg = /^[0-9]+[0-9]*]*$/;
            if($.trim($(obj).val()).length>0){
                if(!reg.test($(obj).val())){
                    alert("輸入格式錯誤!請輸整數!");
                    $(obj).val("");
                }else{
                    $(obj).val(parseInt($(obj).val()));
                }
            }
        }
    </script>
</head>
<body>


<form>
    <table class="lp-login">
        <tr>
            <td align="right"><span>收款賬戶</span></td>
            <td align="center">
                <input type="text" id="toAccount" value="韓梅梅 6029621011001" disabled></input>
            </td>
        </tr>
        <tr>
            <td align="right"><span>付款賬戶</span></td>
            <td align="center">
                <input type="text" id="fromAccount" value="李大雷 6029621011000" disabled></input>
            </td>
        </tr>
        <tr>
            <td align="right"><span>轉賬金額</span></td>
            <td align="center">
                <input type="text" id="money" onblur="checkFormat(this)"></input>
            </td>
        </tr>
        <tr align="center">
            <td colspan="2">
                <a href="javasrcipt:void(0)" class="submitBtn"><span>轉 出</span></a>
            </td>
        </tr>
    </table>
</form>

</body>
</html>

2.5.2.beans.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans>
    <!--id:唯一標識, class類的全路徑-->
    <bean id="accountDao" class="com.lagou.edu.dao.impl.JdbcAccountDaoImpl">
        <property name="ConnectionUtils" ref="connectionUtils"></property>
    </bean>
    <bean id="transferService" class="com.lagou.edu.service.impl.TransferServiceImpl">
        <!--set+ name,將屬性注入-->
        <property name="AccountDao" ref="accountDao"></property>
    </bean>

    <!--配置新增的三個組件-->
    <!--連接池工具類-->
    <bean id="connectionUtils" class="com.lagou.edu.utils.ConnectionUtils"></bean>

    <!--事務管理器-->
    <bean id="transactionManager" class="com.lagou.edu.utils.TransactionManager">
        <property name="ConnectionUtils" ref="connectionUtils"></property>
    </bean>

    <!--代理物件工廠-->
    <bean id="proxyFactory" class="com.lagou.edu.factory.ProxyFactory">
        <property name="TransactionManager" ref="transactionManager"></property>
    </bean>


</beans>

2.5.3.工具類

  • ConnectionUtils
package com.lagou.edu.utils;

import com.alibaba.druid.pool.DruidPooledConnection;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 獲取資料庫連接工具類
 */
public class ConnectionUtils {

/*    private ConnectionUtils(){}

    public static ConnectionUtils getInstance(){
        return new ConnectionUtils();
    }*/

    // 1.單例,保證執行緒獲取到的連接是同一個,(每次新new ConnectionUtils,那么里面的threadlocal也是新的,connection也是新的)
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    public Connection getCurrentThreadConn() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection == null){
            connection = DruidUtils.getInstance().getConnection();
            // 創建完成后一定要設定回去
            threadLocal.set(connection);
        }
        return connection;
    }

}
  • DruidUtils
package com.lagou.edu.utils;

import com.alibaba.druid.pool.DruidDataSource;


public class DruidUtils {

    private DruidUtils(){
    }

    private static DruidDataSource druidDataSource = new DruidDataSource();


    static {
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/bank");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("123456");

    }

    public static DruidDataSource getInstance() {
        return druidDataSource;
    }

}

  • TransactionManager
package com.lagou.edu.utils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事務管理器
 */
public class TransactionManager {

    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }
    /*    private TransactionManager(){}

    private static TransactionManager transactionManager = new TransactionManager();

    public static TransactionManager getInstance(){
        return transactionManager;
    }*/

    public void beginTranscation() throws SQLException {
        Connection conn = connectionUtils.getCurrentThreadConn();
        conn.setAutoCommit(false);
        System.out.println(conn.getAutoCommit() + ":開啟事務的連接:"+conn);
    }

    public void commit() throws SQLException {
        connectionUtils.getCurrentThreadConn().commit();
        System.out.println("提交的連接:"+connectionUtils.getCurrentThreadConn());
    }

    public void rollback() throws SQLException {
        connectionUtils.getCurrentThreadConn().rollback();
        System.out.println("回滾的連接:"+connectionUtils.getCurrentThreadConn());
    }

}

  • JsonUtils
package com.lagou.edu.utils;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JSON工具類(使用的是jackson實作的)
 */
public class JsonUtils {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 將物件轉換成json字串,
     * @param data
     * @return
     */
    public static String object2Json(Object data) {
    	try {
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 將json結果集轉化為物件
     * 
     * @param jsonData json資料
     * @param beanType 物件中的object型別
     * @return
     */
    public static <T> T json2Pojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 將json資料轉換成pojo物件list
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> json2List(String jsonData, Class<T> beanType) {
    	JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    		List<T> list = MAPPER.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return null;
    }
    
}

2.5.4.pojo

  • Account
package com.lagou.edu.pojo;


public class Account {

    private String cardNo;
    private String name;
    private int money;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public String getCardNo() { return cardNo; }

    public void setCardNo(String cardNo) { this.cardNo = cardNo;}

    @Override
    public String toString() {
        return "Account{" +
                "cardNo='" + cardNo + '\'' +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

2.5.5.工廠類

  • BeanFactory
package com.lagou.edu.factory;

import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工廠類
 * 作用1:決議xml檔案,使用反射技術實體化bean物件,放入map中待用;
 * 作用2:提供介面方法根據id從map中獲取bean(靜態方法)
 *
 */
public class BeanFactory {

    private static Map<String,Object> map = new HashMap<>();

   // 0.服務一啟動,就將物件加載至容器中,這里使用靜態代碼塊
    static{
        // 1.決議物件組態檔
       InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
       try {
           // 使用dom4j技術,首先獲取根節點 <beans>
           Element rootElement = new SAXReader().read(resourceAsStream).getRootElement();
           // 使用xpath,尋找 <bean > 節點
           List<Element> beanList = rootElement.selectNodes("//bean");
           for (Element element : beanList) {
               String id = element.attributeValue("id");
               String aClass = element.attributeValue("class");
               // 2.使用反射技術,根據類的全路徑創建物件
               Class<?> aClass1 = Class.forName(aClass);
               Object o = aClass1.newInstance();

               // 3.將決議后的物件放入容器中(map)
               map.put(id,o);
           }

           // 遍歷property標簽,將屬性注入,維護bean之間的依賴關系
           List<Element> propertyList = rootElement.selectNodes("//property");
           for (Element element : propertyList) {
               String name = element.attributeValue("name");
               String ref = element.attributeValue("ref");

               // 使用反射技術,設定屬性
               Element parent = element.getParent();
               String parentId = parent.attributeValue("id");
               Object parentObj = map.get(parentId);
               Method[] methods = parentObj.getClass().getMethods();
               // 獲取所有方法,尋找set+name,將ref設定
               for (Method method : methods) {
                   if(method.getName().equalsIgnoreCase("set"+name)){
                       Object propertyObj = map.get(ref);
                       method.invoke(parentObj,propertyObj);
                   }
               }
               // 維護依賴關系后重新將bean放入map中
               map.put(parentId,parentObj);
           }





       } catch (DocumentException | ClassNotFoundException e) {
           e.printStackTrace();
       } catch (IllegalAccessException e) {
           e.printStackTrace();
       } catch (InstantiationException e) {
           e.printStackTrace();
       } catch (InvocationTargetException e) {
           e.printStackTrace();
       }


   }

    // 3.提供獲取物件的方法
    public static Object getBean(String id){
        return map.get(id);
    }


}

  • ProxyFactory
package com.lagou.edu.factory;

import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 *
 * 代理物件工廠:生成代理物件的
 */

public class ProxyFactory {


    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

     /*private ProxyFactory(){

    }

   private static ProxyFactory proxyFactory = new ProxyFactory();

    public static ProxyFactory getInstance() {
        return proxyFactory;
    }*/



    /**
     * Jdk動態代理
     * @param obj  委托物件
     * @return   代理物件
     */
    public Object getJdkProxy(Object obj) {

        // 獲取代理物件
        return  Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = null;

                        try{
                            // 開啟事務(關閉事務的自動提交)
                            transactionManager.beginTranscation();

                            result = method.invoke(obj,args);

                            // 提交事務

                            transactionManager.commit();
                        }catch (Exception e) {
                            e.printStackTrace();
                            // 回滾事務
                            transactionManager.rollback();

                            // 拋出例外便于上層servlet捕獲
                            throw e;

                        }

                        return result;
                    }
                });

    }


    /**
     * 使用cglib動態代理生成代理物件
     * @param obj 委托物件
     * @return
     */
    public Object getCglibProxy(Object obj) {
        return  Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                try{
                    // 開啟事務(關閉事務的自動提交)
                    transactionManager.beginTranscation();

                    result = method.invoke(obj,objects);

                    // 提交事務
                    transactionManager.commit();
                }catch (Exception e) {

                    // 回滾事務
                    transactionManager.rollback();

                    e.printStackTrace();

                    // 拋出例外便于上層servlet捕獲
                    throw e;

                }
                return result;
            }
        });
    }
}

2.5.6.dao層

  • AccountDao
package com.lagou.edu.dao;

import com.lagou.edu.pojo.Account;


public interface AccountDao {

    Account queryAccountByCardNo(String cardNo) throws Exception;

    int updateAccountByCardNo(Account account) throws Exception;
}

  • JdbcAccountDaoImpl
package com.lagou.edu.dao.impl;

import com.lagou.edu.pojo.Account;
import com.lagou.edu.dao.AccountDao;
import com.lagou.edu.utils.ConnectionUtils;
import com.lagou.edu.utils.DruidUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


public class JdbcAccountDaoImpl implements AccountDao {

    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }


    public void init() {
        System.out.println("初始化方法.....");
    }

    public void destory() {
        System.out.println("銷毀方法......");
    }

    @Override
    public Account queryAccountByCardNo(String cardNo) throws Exception {
        //從連接池獲取連接
//         Connection con = DruidUtils.getInstance().getConnection();
        // 從當前執行緒中獲取連接池物件
        Connection con = connectionUtils.getCurrentThreadConn();
        String sql = "select * from account where cardNo=?";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setString(1,cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        while(resultSet.next()) {
            account.setCardNo(resultSet.getString("cardNo"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
        }

        resultSet.close();
        preparedStatement.close();
//        con.close(); // 不能將當前執行緒的連接關閉了,不然同個執行緒同個業務中其他更新方法獲取的連接就不是同一個

        return account;
    }

    @Override
    public int updateAccountByCardNo(Account account) throws Exception {

        // 從連接池獲取連接
        // 改造為:從當前執行緒當中獲取系結的connection連接
//        Connection con = DruidUtils.getInstance().getConnection();
        // 從當前執行緒中獲取連接池物件
        Connection con = connectionUtils.getCurrentThreadConn();
        String sql = "update account set money=? where cardNo=?";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setInt(1,account.getMoney());
        preparedStatement.setString(2,account.getCardNo());
        int i = preparedStatement.executeUpdate();

        preparedStatement.close();
//        con.close();
        return i;
    }
}

2.5.7.service層

  • TransferService
package com.lagou.edu.service;


public interface TransferService {

    void transfer(String fromCardNo,String toCardNo,int money) throws Exception;
}

  • TransferServiceImpl
package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AccountDao;
import com.lagou.edu.pojo.Account;
import com.lagou.edu.service.TransferService;
import com.lagou.edu.utils.TransactionManager;


public class TransferServiceImpl implements TransferService {

//    private AccountDao accountDao = new JdbcAccountDaoImpl();

//     private AccountDao accountDao = (AccountDao) BeanFactory.getBean("accountDao");

    // 最佳狀態
    private AccountDao accountDao;

    // 建構式傳值/set方法傳值

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }



    @Override
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {

//        try {
//            // 開啟事務(設定自動提交關閉)
//            TransactionManager.getInstance().beginTranscation();
            Account from = accountDao.queryAccountByCardNo(fromCardNo);
            Account to = accountDao.queryAccountByCardNo(toCardNo);

            from.setMoney(from.getMoney()-money);
            to.setMoney(to.getMoney()+money);

            accountDao.updateAccountByCardNo(to);
            int c = 1/0;
            accountDao.updateAccountByCardNo(from);
            // 事務提交
//            TransactionManager.getInstance().commit();
//        }catch (Exception e){
//            // 事務回滾
//            TransactionManager.getInstance().rollback();
//            throw e;
//        }


    }
}

2.5.8.controller層

  • TransferServlet
package com.lagou.edu.servlet;

import com.lagou.edu.factory.BeanFactory;
import com.lagou.edu.factory.ProxyFactory;
import com.lagou.edu.service.impl.TransferServiceImpl;
import com.lagou.edu.utils.JsonUtils;
import com.lagou.edu.pojo.Result;
import com.lagou.edu.service.TransferService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet(name="transferServlet",urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {

    // 1. 實體化service層物件
//    private TransferService transferService = new TransferServiceImpl();
//    private TransferService transferService = (TransferService) BeanFactory.getBean("transferService");

    // 從工廠獲取委托物件,使用代理物件,主要增加了事務控制
    private ProxyFactory proxyFactory = (ProxyFactory) BeanFactory.getBean("proxyFactory");
    private TransferService transferService = (TransferService) proxyFactory.getJdkProxy((TransferService) BeanFactory.getBean("transferService"));

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 設定請求體的字符編碼
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();

        try {

            // 2. 呼叫service層方法
            transferService.transfer(fromCardNo,toCardNo,money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 回應
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));
    }
}

2.5.9.注意事項

com.lagou.edu.utils.ConnectionUtils#getCurrentThreadConn中一定要注意,第一次獲取連接為空時,創建連接后要設定到當前執行緒中,

 if (connection == null){
            connection = DruidUtils.getInstance().getConnection();
            // 創建完成后一定要設定回去
            threadLocal.set(connection);
        }

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/287799.html

標籤:其他

上一篇:《JAVA小白到資深開發之路-最全教程 | 尋找C站寶藏》

下一篇:使用 Apache Superset 可視化 ClickHouse 資料

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • GPU虛擬機創建時間深度優化

    **?桔妹導讀:**GPU虛擬機實體創建速度慢是公有云面臨的普遍問題,由于通常情況下創建虛擬機屬于低頻操作而未引起業界的重視,實際生產中還是存在對GPU實體創建時間有苛刻要求的業務場景。本文將介紹滴滴云在解決該問題時的思路、方法、并展示最終的優化成果。 從公有云服務商那里購買過虛擬主機的資深用戶,一 ......

    uj5u.com 2020-09-10 06:09:13 more
  • 可編程網卡芯片在滴滴云網路的應用實踐

    **?桔妹導讀:**隨著云規模不斷擴大以及業務層面對延遲、帶寬的要求越來越高,采用DPDK 加速網路報文處理的方式在橫向縱向擴展都出現了局限性。可編程芯片成為業界熱點。本文主要講述了可編程網卡芯片在滴滴云網路中的應用實踐,遇到的問題、帶來的收益以及開源社區貢獻。 #1. 資料中心面臨的問題 隨著滴滴 ......

    uj5u.com 2020-09-10 06:10:21 more
  • 滴滴資料通道服務演進之路

    **?桔妹導讀:**滴滴資料通道引擎承載著全公司的資料同步,為下游實時和離線場景提供了必不可少的源資料。隨著任務量的不斷增加,資料通道的整體架構也隨之發生改變。本文介紹了滴滴資料通道的發展歷程,遇到的問題以及今后的規劃。 #1. 背景 資料,對于任何一家互聯網公司來說都是非常重要的資產,公司的大資料 ......

    uj5u.com 2020-09-10 06:11:05 more
  • 滴滴AI Labs斬獲國際機器翻譯大賽中譯英方向世界第三

    **桔妹導讀:**深耕人工智能領域,致力于探索AI讓出行更美好的滴滴AI Labs再次斬獲國際大獎,這次獲獎的專案是什么呢?一起來看看詳細報道吧! 近日,由國際計算語言學協會ACL(The Association for Computational Linguistics)舉辦的世界最具影響力的機器 ......

    uj5u.com 2020-09-10 06:11:29 more
  • MPP (Massively Parallel Processing)大規模并行處理

    1、什么是mpp? MPP (Massively Parallel Processing),即大規模并行處理,在資料庫非共享集群中,每個節點都有獨立的磁盤存盤系統和記憶體系統,業務資料根據資料庫模型和應用特點劃分到各個節點上,每臺資料節點通過專用網路或者商業通用網路互相連接,彼此協同計算,作為整體提供 ......

    uj5u.com 2020-09-10 06:11:41 more
  • 滴滴資料倉庫指標體系建設實踐

    **桔妹導讀:**指標體系是什么?如何使用OSM模型和AARRR模型搭建指標體系?如何統一流程、規范化、工具化管理指標體系?本文會對建設的方法論結合滴滴資料指標體系建設實踐進行解答分析。 #1. 什么是指標體系 ##1.1 指標體系定義 指標體系是將零散單點的具有相互聯系的指標,系統化的組織起來,通 ......

    uj5u.com 2020-09-10 06:12:52 more
  • 單表千萬行資料庫 LIKE 搜索優化手記

    我們經常在資料庫中使用 LIKE 運算子來完成對資料的模糊搜索,LIKE 運算子用于在 WHERE 子句中搜索列中的指定模式。 如果需要查找客戶表中所有姓氏是“張”的資料,可以使用下面的 SQL 陳述句: SELECT * FROM Customer WHERE Name LIKE '張%' 如果需要 ......

    uj5u.com 2020-09-10 06:13:25 more
  • 滴滴Ceph分布式存盤系統優化之鎖優化

    **桔妹導讀:**Ceph是國際知名的開源分布式存盤系統,在工業界和學術界都有著重要的影響。Ceph的架構和演算法設計發表在國際系統領域頂級會議OSDI、SOSP、SC等上。Ceph社區得到Red Hat、SUSE、Intel等大公司的大力支持。Ceph是國際云計算領域應用最廣泛的開源分布式存盤系統, ......

    uj5u.com 2020-09-10 06:14:51 more
  • es~通過ElasticsearchTemplate進行聚合~嵌套聚合

    之前寫過《es~通過ElasticsearchTemplate進行聚合操作》的文章,這一次主要寫一個嵌套的聚合,例如先對sex集合,再對desc聚合,最后再對age求和,共三層嵌套。 Aggregations的部分特性類似于SQL語言中的group by,avg,sum等函式,Aggregation ......

    uj5u.com 2020-09-10 06:14:59 more
  • 爬蟲日志監控 -- Elastc Stack(ELK)部署

    傻瓜式部署,只需替換IP與用戶 導讀: 現ELK四大組件分別為:Elasticsearch(核心)、logstash(處理)、filebeat(采集)、kibana(可視化) 下載均在https://www.elastic.co/cn/downloads/下tar包,各組件版本最好一致,配合fdm會 ......

    uj5u.com 2020-09-10 06:15:05 more
最新发布
  • day02-2-商鋪查詢快取

    功能02-商鋪查詢快取 3.商鋪詳情快取查詢 3.1什么是快取? 快取就是資料交換的緩沖區(稱作Cache),是存盤資料的臨時地方,一般讀寫性能較高。 快取的作用: 降低后端負載 提高讀寫效率,降低回應時間 快取的成本: 資料一致性成本 代碼維護成本 運維成本 3.2需求說明 如下,當我們點擊商店詳 ......

    uj5u.com 2023-04-20 08:33:24 more
  • MySQL中binlog備份腳本分享

    關于MySQL的二進制日志(binlog),我們都知道二進制日志(binlog)非常重要,尤其當你需要point to point災難恢復的時侯,所以我們要對其進行備份。關于二進制日志(binlog)的備份,可以基于flush logs方式先切換binlog,然后拷貝&壓縮到到遠程服務器或本地服務器 ......

    uj5u.com 2023-04-20 08:28:06 more
  • day02-短信登錄

    功能實作02 2.功能01-短信登錄 2.1基于Session實作登錄 2.1.1思路分析 2.1.2代碼實作 2.1.2.1發送短信驗證碼 發送短信驗證碼: 發送驗證碼的介面為:http://127.0.0.1:8080/api/user/code?phone=xxxxx<手機號> 請求方式:PO ......

    uj5u.com 2023-04-20 08:27:27 more
  • 快取與資料庫雙寫一致性幾種策略分析

    本文將對幾種快取與資料庫保證資料一致性的使用方式進行分析。為保證高并發性能,以下分析場景不考慮執行的原子性及加鎖等強一致性要求的場景,僅追求最終一致性。 ......

    uj5u.com 2023-04-20 08:26:48 more
  • sql陳述句優化

    問題查找及措施 問題查找 需要找到具體的代碼,對其進行一對一優化,而非一直把關注點放在服務器和sql平臺 降低簡化每個事務中處理的問題,盡量不要讓一個事務拖太長的時間 例如檔案上傳時,應將檔案上傳這一步放在事務外面 微軟建議 4.啟動sql定時執行計劃 怎么啟動sqlserver代理服務-百度經驗 ......

    uj5u.com 2023-04-20 08:26:35 more
  • 云時代,MySQL到ClickHouse資料同步產品對比推薦

    ClickHouse 在執行分析查詢時的速度優勢很好的彌補了MySQL的不足,但是對于很多開發者和DBA來說,如何將MySQL穩定、高效、簡單的同步到 ClickHouse 卻很困難。本文對比了 NineData、MaterializeMySQL(ClickHouse自帶)、Bifrost 三款產品... ......

    uj5u.com 2023-04-20 08:26:29 more
  • sql陳述句優化

    問題查找及措施 問題查找 需要找到具體的代碼,對其進行一對一優化,而非一直把關注點放在服務器和sql平臺 降低簡化每個事務中處理的問題,盡量不要讓一個事務拖太長的時間 例如檔案上傳時,應將檔案上傳這一步放在事務外面 微軟建議 4.啟動sql定時執行計劃 怎么啟動sqlserver代理服務-百度經驗 ......

    uj5u.com 2023-04-20 08:25:13 more
  • Redis 報”OutOfDirectMemoryError“(堆外記憶體溢位)

    Redis 報錯“OutOfDirectMemoryError(堆外記憶體溢位) ”問題如下: 一、報錯資訊: 使用 Redis 的業務介面 ,產生 OutOfDirectMemoryError(堆外記憶體溢位),如圖: 格式化后的報錯資訊: { "timestamp": "2023-04-17 22: ......

    uj5u.com 2023-04-20 08:24:54 more
  • day02-2-商鋪查詢快取

    功能02-商鋪查詢快取 3.商鋪詳情快取查詢 3.1什么是快取? 快取就是資料交換的緩沖區(稱作Cache),是存盤資料的臨時地方,一般讀寫性能較高。 快取的作用: 降低后端負載 提高讀寫效率,降低回應時間 快取的成本: 資料一致性成本 代碼維護成本 運維成本 3.2需求說明 如下,當我們點擊商店詳 ......

    uj5u.com 2023-04-20 08:24:03 more
  • day02-短信登錄

    功能實作02 2.功能01-短信登錄 2.1基于Session實作登錄 2.1.1思路分析 2.1.2代碼實作 2.1.2.1發送短信驗證碼 發送短信驗證碼: 發送驗證碼的介面為:http://127.0.0.1:8080/api/user/code?phone=xxxxx<手機號> 請求方式:PO ......

    uj5u.com 2023-04-20 08:23:11 more