Springフレームワークは、ソフトウェア開発の複雑さのために作成されます。 Springは、基本的なJavabeansを使用して、以前はEJBによってのみ可能だったことを行います。ただし、Springの目的は、サーバー側の開発に限定されません。シンプルさ、テスト可能性、ゆるい結合の観点から、ほとんどのJavaアプリケーションは春の恩恵を受けることができます。 Springは、軽量制御反転(IOC)とセクション指向(AOP)コンテナフレームワークです。
◆目的:エンタープライズアプリケーション開発の複雑さを解決します
◆機能:EJBの代わりにBasic Javabeanを使用し、より多くのエンタープライズアプリケーション機能を提供します
◆スコープ:Javaアプリケーション
制御の反転(英語の略語のIOC)は、フレームワークの重要な機能であり、オブジェクト指向プログラミングの特別な用語ではないフレームワークにオブジェクトを作成する権利を与えます。依存関係の注入と依存関係の検索が含まれます。従来のビジネスレイヤーでは、リソースが必要な場合、新しいリソースがビジネス層で見つかり、カップリング(相互依存とプログラム間の相関)が高くなります。ここで、新しい部分を春に渡して、高い結束と低カップリングを実現します。要するに、元々、DAOレイヤーまたはサービスレイヤーメソッドが呼び出されたときはいつでも、アプリは新しいものを使用し、今では新しい権利が春に引き渡され、必要なリソースが春から得られました!
1.フレームワークに必要な依存関係JARパッケージをダウンロードする
公式の春のウェブサイトは次のとおりです:http://spring.io/
jarパッケージをダウンロード:http://repo.springsource.org/libs-release-local/org/springframework/spring
2。基本的なJARパッケージをインポートします
実際、基本的なコアジャーには豆;コンテキスト;コア、式パッケージ、その他はlog4jログに依存します。もちろん、春の瓶はそれ以上のものであり、後の段階でゆっくりと追加されます。
3. log4j構成ファイルを構成します
ログファイルは、SRCディレクトリで定義されています
### stdoutにログメッセージを直接### log4j.appender.stdout = org.apache.log4j.consoleappenderlog4j.appender.stdout.target = system.errlog4j.appender.stdout.layout = org.apache.log4j.patternlayoutlog4j.apptern.stdout.layout.conurs.patrut.conurs.patrut.conurs.conurs.patrut. %c {1}:%l -%m%n ### file mylog.logへの直接メッセージ### log4j.appender.file = org.apache.log4j.fileappenderlog4j.appender.file.file = c/:mylog.loglog4j.appender.file.layout = org.apache.log4j.patternlayoutlog4j4j4j {daptern.patrut.conurs.conurs.conurs.patrut.conurs %c {1}:%l-%m%n ###ログレベルを設定 - 詳細記録のために「debug」に「情報」を変更する### log4j.rootlogger = info、stdout4.ログファイルが正常に展開されているかどうかをテストします
パッケージcom.clj.demo1; import org.apache.log4j.logger; Import org.junit.test;/** * demo log usage * @author Administrator * */public class demo1 {//ログクラスのプライベートロガー= logger.getlogger(demo1.class); @test public void run1(){// log4j.rootlogger属性の情報をOFFに変更し、log.info( "execute"); }}5.インターフェイスを定義し、クラスを実装します
インタフェース:
パッケージcom.clj.demo2; public interface userservice {public void sayshello();}実装クラス
パッケージcom.clj.demo2; public class userserviceimplを実装します{private string name; public string getName(){return name; } public void setName(string name){this.name = name; } public void init(){system.out.println( "initialize .."); } public void sayshello(){system.out.println( "hello spring"+"/t"+name); } public void destory(){system.out.println( "Destroy .."); }}6.スプリング固有の構成ファイルを定義します
ApplicationContext.xmlの名前を定義します。場所は、ログファイルと同じディレクトリであるSRC、対応する制約をインポートし、実装クラスを構成ファイルに挿入します。最初から始めて、Beanの制約を使用してください
<?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:p = "http://www.springframework.org/schema/p" xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/ Beanタグ1を使用します。ID値は一意です(書き込みマスト) </bean> </bean>
7。テスト
public class demo1 { /*** original way* /@test public void run(){//実装クラスuserserviceimpl s = new userserviceimpl(); S.SetName( "Jaxiansen"); S.Sayhello(); } / ***古い工場バージョンBeanFactory*古い工場は構成ファイルオブジェクトを作成しませんuserservice us =(userservice)factory.getbean( "userservice"); us.sayhello(); } /***スプリングフレームワークの使用IOCメソッド*ファクトリーの新しいバージョンで起動サーバーを作成して構成ファイルオブジェクトを作成します。もう一度呼び出すときに工場をロードする必要はありません* /@Test public void run3(){//コア構成ファイルをロードしてロードし、ClassPathxmlApplicationContex classPathXMLApplicationContext( "ApplicationContext.xml"); //工場からオブジェクトを取得します(構成ファイルのID値、Polymorphismはここで使用されます)userservice usi =(userservice)ac.getBean( "userservice"); // usi.sayhello()を実行するためのオブジェクトのメソッドを呼び出す; } /*** DEMO DESTURTY-METHODメソッド* Bean Destroyメソッドは自動的に実行されません* Scope = SingletonまたはWebコンテナで自動的に呼び出されない限り、メイン機能またはテストケースは、Class PathxmlapplicationContextのclose()メソッドを使用する必要があります()パブリックvoid run4() (classpathxmlapplicationcontextはsrcの下にあります)classpathxmlapplicationcontext ac = new classpathxmlapplicationContext( "ApplicationContext.xml"); //工場からオブジェクトを取得します(構成ファイルのID値、Polymorphismはここで使用されます)userservice usi =(userservice)ac.getBean( "userservice"); // usi.sayhello()を実行するためのオブジェクトのメソッドを呼び出す; // ApplicationContextの実装クラスは密接な方法を提供し、工場を閉じてDestory-Methodメソッドを実行できます。 }}古い工場と新しい工場の違い
* BeanFactoryとApplicationContextの違い
* BeanFactory -BeanFactoryは怠zyな負荷を取り、Beanは初めてGetBeanを取得したときにのみ初期化されます
* ApplicationContext -ApplicationContext.xmlをロードすると、Beanオブジェクトの特定のインスタンスが作成され、他の機能が提供されます。
*イベント配信
* Bean Automatic Assembly
*さまざまなアプリケーションレイヤーのコンテキスト実装
概要:これは、実装クラスをSpring構成ファイルに構成する最も基本的なデモです。サーバーが開始されるたびに、構成ファイルがロードされ、実装クラスがインスタンス化されます。
1。依存関係噴射とは何ですか?
Springは、J2EEアプリケーションレベルのオブジェクトを効果的に整理できます。制御レイヤーのアクションオブジェクト、ビジネスレイヤーのサービスオブジェクト、または永続レイヤーのDAOオブジェクトであろうと、Springの管理下で有機的に調整して実行できます。スプリングは、各レイヤーのオブジェクトをゆるく結合した方法で一緒に整理します。アクションオブジェクトは、サービスオブジェクトの特定の実装を気にする必要はなく、サービスオブジェクトは永続的なレイヤーオブジェクトの特定の実装を気にする必要はありません。各レイヤーオブジェクトへの呼び出しは完全にインターフェイス指向です。システムをリファクタリングする必要がある場合、コードの書き換えの量は大幅に削減されます。依存関係の噴射により、ハードコードではなく、構成ファイルで豆と豆が整理されます。依存関係の注入を理解します
依存関係の注入と制御の反転は同じ概念です。具体的な意味は、役割(Javaインスタンス、発信者)が別の役割(別のJavaインスタンス、発信者)の支援を必要とする場合、従来のプログラミングプロセスでは、発信者は通常発信者によって作成されます。しかし、春には、Calleeの作成作業は発信者によって行われなくなったため、コントロール反転と呼ばれます。 Calleeインスタンスの作成作業は通常、スプリングコンテナによって行われ、発信者に注入されるため、依存関係噴射とも呼ばれます。
依存関係の注入であろうとコントロールの反転であろうと、Springはさまざまなオブジェクトを管理する動的で柔軟な方法を採用することを意味します。オブジェクト間の特定の実装は、互いに透明です。
2。IOCとDIの概念
* IOC-コントロールの逆、制御の反転、オブジェクトの作成権をスプリングに反転させます! !
* DI-依存関係の注入、依存関係噴射、スプリングフレームワークがBeanオブジェクトの作成に責任がある場合、Beanコンポーネントに依存性オブジェクトを動的に注入します! !
3。デモ
クラスのメンバー変数には、2つの一般的な注入方法があります。
プロパティセットメソッドインジェクションおよびコンストラクターメソッドインジェクション
最初に最初のタイプ:プロパティセットメソッドインジェクションを示します
1)永続的なレイヤー
パッケージcom.clj.demo3; public class customerdaoimpl {public void save(){system.out.println( "私は永続性レイヤーのダオです"); }}2)ビジネスレイヤー
注:現時点では、永続レイヤーをビジネスレイヤーに注入し、右を渡して、フレームワークに永続性レイヤーインスタンスを作成するために右を引き渡したいと思います。条件は、ビジネスレイヤーがメンバー属性を提供し、永続レイヤーのメソッドを設定する必要があることです。
パッケージcom.clj.demo3;/** *依存関係インジェクションDAOレイヤーをサービスレイヤーに注入 * @Author Administrator * */Public Class CustomerServiceImpl {//メンバーZODIACを提供し、SETメソッドプライベートカスタマーダオイムプルCustomerDaoを提供します。 public void setcustomerdao(customerdaoimpl customerdao){this.customerdao = customerdao; } public void save(){system.out.println( "私はサービス..."); // 1。元の方法// new CustomerDaoimpl()。save(); //2.SPRING IOCメソッドCustomerDao.save(); }}3)構成ファイル構成
<! - デモンストレーション依存関係インジェクション - > <bean id = "customerdao"/> <bean id = "customerservice"> <! - daoをサービスレイヤーに注入 - > <プロパティ名= "customerdao" ref = "customerdao"> </property> </bean> </bean>
4)テスト
/** *スプリング依存関係インジェクションメソッド * DAOレイヤーをサービスレイヤーに注入 */@Test public void run2(){//ファクトリーを作成し、構成ファイルをロードすると、顧客ApplicationContext Context = new ClassPathxMLApplicationContext( "ApplicationContext.xml"); customerserviceimpl csi =(customerserviceimpl)context.getBean( "customerservice"); csi.save(); }2番目のタイプ:建設方法注入
1)POJOクラスとコンストラクターの方法を提供します
パッケージcom.clj.demo4;/** *デモインジェクションメソッド * @author管理者 * */public class car1 {private string cname;プライベートダブル価格。 public car1(string cname、double price){super(); this.cname = cname; this.price = price; } @Override public String toString(){return "car1 [cname =" + cname + "、firce =" + fires + "]"; }}2)構成ファイル構成
<! - 建設方法の注入方法を実証します - > <bean id = "car1"> <! - 書き込み方法1 <constructor-arg name = "cname-arg" value = "bmw"/> <constructor-arg name = "rish" value = "400000"/> - > <! - 書き込み方法value = "400000"/> </bean>
3)テスト
@test public void run1(){applicationContext ac = new classpathxmlapplicationContext( "applicationContext.xml"); car1 car =(car1)ac.getbean( "car1"); System.out.println(car); }拡張:構築方法は、あるオブジェクトを別のオブジェクトに注入します
1)Pojoクラス:目的:上記の列の車を人間に注入し、属性の1つにします。このクラスでは、車のメンバー属性を提供し、パラメーター化された建設方法を提供する必要があります。
パッケージcom.clj.demo4; public class person {private string name; Private Car1 Car1; public Person(string name、car1 car1){super(); this.name = name; this.car1 = car1; } @Override public String toString(){return "person [name =" + name + "、car1 =" + car1 + "]"; }}2)構成ファイル
<! - constructor-arg name = "name" value = "jaxiansen"/> <constructor-arg name = "car1" ref = "car1"/> </bean>
4.コレクションアレイを注入する方法
1)Pojoクラスを定義します
パッケージcom.clj.demo4; import java.util.arrays; import java.util.list; import java.util.map; import java.util.properties; import java.util.set;/** *インジェクションを設定する方法を実証します * @author管理者 *プライベートリスト<文字列>リスト;プライベートセット<文字列>セット;プライベートマップ<文字列、文字列>マップ; Private Properties Pro; public void setPro(Properties Pro){this.pro = pro; } public void setsets(set <string> sets){this.sets = sets; } public void setMap(map <string、string> map){this.map = map; } public void setlist(list <string> list){this.list = list; } public void setArrrs(string [] arrrs){this.arrs = arrrs; } @Override public String toString(){return "user [arrs =" + arrays.tostring(arrs) + "、list =" + list + "、sets =" + sets + "、map =" + map + "、pro =" + pro + "]"; }}2)構成ファイル
<! - インジェクションセット - > <bean id = "user"> <! - array-> <プロパティ名= "arrs"> <list> <balue> number1 </value> <balue> number2 </value> <balue> number3 </value> </list> </property> < </property> <! - set set-> <プロパティ名= "sets"> <set> <balue> haha </value> <balue> haha </value> </set> </property> <! - マップセット - > <プロパティ名= "マップ"> <エントリキー= "aa" value = "rainbow"/> <entry key = "balenus"/> <プロパティ名= "pro"> <props> <prop key = "username"> root </prop> <prop key = "password"> 123 </prop> </props> </property> </bean>
3)テスト
/ ***インジェクションコレクションをテスト*/ @test public void run3(){applicationContext AC = new ClassPathxMLApplicationContext( "ApplicationContext.xml"); user user =(user)ac.getbean( "user"); System.out.println(user); }5.モジュールで開発する方法
メイン構成ファイルに<Import>タグを追加します(構成ファイルApplicationContext2.xmlがcom.clj.testパッケージで定義されていると仮定します)
<! - モジュール開発による他の構成ファイルの導入 - > <リソースをインポート= "com/clj/test/applicationcontext2.xml"/>
1。始めましょう
1).IMPORT JARパッケージ
前の6つのパッケージに加えて、注釈を再生するにはスプリングAOPパッケージも必要です。
2)。永続レイヤーと実装レイヤー(ここではインターフェイスが無視されます)
永続的なレイヤー
パッケージcom.clj.demo1; Import org.springframework.context.annotation.scope; Import org.springframework.streleotype.component; import org.springframework.stertoty.repository; userdao {@Override public void save(){system.out.println( "client the client .."); }}ビジネス層
パッケージcom.clj.demo1; import javax.annotation.postconstruct; import org.springframework.beans.factory.annotation.autowired; Import org.springframework.factory.annotation.Annotation.Qualifier; Import org.springframework.beans.beans.value; value; org.springframework.stereotype.component; public class userserviceimpl explence userservice {@override public void sayshello(){system.out.println( "hello spring"); }}3)。構成ファイルを定義します
この時点で、制約はコンテキストの制約を追加し、コンポーネントスキャンを追加する必要があります
<?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:context = "http://www.springframework.org/schema/context" xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.orgwork.org/schems.spring/ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd base-package = "com.clj.demo1"/> </beans>
4)実装クラスに注釈を追加します
/***コンポーネントアノテーション。これは、現在のクラスをマークするために使用できます* <bean id = "userservice">* valueは、クラスのエイリアスを与えることを意味します*/@component(value = "userservice")public class userserviceimpl emprentice userservice {//省略}5)テストを書きます
/ *** annotation Method*/ @test public void run2(){applicationContext AC = new ClassPathxMLApplicationContext( "ApplicationContext.xml"); userservice us =(userservice)ac.getbean( "userservice"); us.sayhello(); }2。豆管理の共通属性について
1。@Component:コンポーネント。 (クラスで行動しました)最も原始的な注釈、注釈が必要なすべてのクラスについてこれを書いても大丈夫です、それは一般的です
2。@Componentの3つの派生注釈が春に提供されます:(関数は現在一貫しています)
* @Controller- Webレイヤーで動作します
* @Service-ビジネスレベルで行動します
* @Repository-永続レイヤーに作用します
*注:これら3つの注釈は、注釈クラス自体の目的を明確にすることを目的としており、Springは後続のバージョンでそれを強化します。
3。属性注入の注釈(注:注釈注入を使用する場合、設定された方法を提供する必要はありません)
*通常のタイプの注入の場合、値注釈を使用できます
* @Value-通常のタイプを注入するため
*注入されたオブジェクトタイプの場合は、次の注釈を使用します
* @Autowired-デフォルトでは、タイプはタイプごとに自動的に組み立てられ、注入クラスのクラス名とは何の関係もありません。
*名前で注入する場合
* @qualifier-名前の強制的な使用は、自動化されたもので使用し、クラス名を指定し、注入されたクラス名に関連する必要があります
* @Resource- @autowiredおよび @qualifierに相当します
*強調:Javaが提供する注釈
*属性は名前属性を使用します
4。豆の範囲の注釈
* @scope(value = "Prototype")として注釈。クラスで使用されます。値は次のとおりです。
*シングルトン - シングルトン、デフォルト値
*プロトタイプ - 複数のケース
5。豆のライフサイクルの構成(理解)
*注釈は次のとおりです。
* @PostConstruct- init-methodに相当します
* @predestroy-破壊と同等
1.属性オブジェクトアノテーションを実証します
条件:スキャンして、属性(名前)とオブジェクト(userdaoimpl)をビジネスレイヤーに注入します。
1)持続層を開き、注釈をスキャンします
//@component(value = "userdao")Universal class annotation@repository(value = "ud")public class userdaoimpl emprences userdao {@override public void save(){system.out.println( "client the client .."); }}2)ビジネスレイヤーは、属性とオブジェクトの注釈を提供します
パッケージcom.clj.demo1; import javax.annotation.postconstruct; import org.springframework.beans.factory.annotation.autowired; Import org.springframework.factory.annotation.Annotation.Qualifier; Import org.springframework.beans.beans.value; value; org.springframework.stereotype.component;/** *コンポーネントアノテーションは、<bean id = "userservice"> * valueと同様の現在のクラス *をマークするために使用できます。 //属性注釈:指定された文字列を名前属性に注入することと同等です。 setNameメソッドは、@value(value = "Jaxiansen")プライベート文字列名を書くことなく省略できます。 /** *参照注入方法1:Autowired() *参照噴射方法2:Autowired() +修飾子@qualifier(value = "ud")//名前によるインジェクション、Autowiredで使用する必要があります。どちらもクラスのプライベートユーザーダオuserdaoを指定できます。 //修飾子の値は、userdaoimplクラス名の上部の注釈名であるか、構成ファイルでビーンのID名を指定できることに注意してください/*public void setName(string name){this.name = name; }*/ @Override public void sayshello(){system.out.println( "hello spring"+name); userdao.save(); } // @postconstructアクションの初期化のためのタグアノテーションlifecycle @postconstruct public void init(){system.out.println( "initialize ..."); }}3)構成ファイルは、すべての構成ファイルをスキャンするために有効にする必要があります
<?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:context = "http://www.springframework.org/schema/context" xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.orgwork.org/schems.spring/ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd base-package = "com.clj.demo1"/> </beans>
注:コレクションについては、構成ファイルを使用することをお勧めします
2。スプリングフレームワークは、Junitユニットテストを統合します
1)必要な依存関係パッケージSpring-Test.jarを追加します
注:MyEclipesには独自のJunit環境が付属していますが、バージョンの問題が原因で、新しいJunit環境が必要になる場合があります。ここでは、新しいJunit-4.9 Jarパッケージをオンラインでダウンロードしました。 MyEclipesが新しい場合は、考慮する必要はありません。
2)テストクラスを書き、対応する注釈を追加します
@runwithおよび@contextconfiguration(これは、Webrootからのデフォルトのパスが第1レベルのディレクトリであるため、構成ファイルのロードに使用されます。さらに、SRCが最初のレベルのディレクトリであると判断するためです)
パッケージcom.clj.demo2; Import javax.annotation.resource; import org.junit.test; import org.junit.runner.runwith; import org.springframework.test.context.contextconfiguration; Import org.springframework.test.context.context.context.context.context.context.context.context.context.context.context.contex com.clj.demo1.userservice; @runwith(springjunit4classrunner.class)@contextconfiguration( "classpath:applicationcontext.xml")public class demo2 {@resource(name = "userservice")private userservice userservice; @test public void run1(){userservice.sayhello(); }}6。スプリングフレームワークのAOP
1. AOPとは
*ソフトウェア業界では、AOPはアスペクト指向プログラミングの略語です。つまり、ファセットプログラミング、機能的モジュール性
* AOPはプログラミングパラダイムであり、ソフトワークのカテゴリに所属し、開発者にプログラム構造を整理する方法を導きます
* AOPは最初にAOP Alliance Organizationによって提案され、一連の規範を策定しました。 SpringはAOPのアイデアをフレームワークに導入し、AOP Allianceの仕様を順守する必要があります。
*ランタイム中に事前コンパイルとダイナミックエージェントを通じてプログラム機能の統一されたメンテナンスを実現するためのテクノロジー
* AOPは、OOPの継続であり、ソフトウェア開発のホットトピック、Springフレームワークの重要な部分、および機能プログラミングの派生パラダイムです。
* AOPを使用して、ビジネスロジックのさまざまな部分を分離し、それにより、ビジネスロジックの部分間の結合を減らし、プログラムの再利用性を改善し、開発の効率を改善することができます。
AOPは水平抽出メカニズムを採用し、従来の垂直継承システムの繰り返しコードを置き換えます(パフォーマンス監視、トランザクション管理、セキュリティ検査、キャッシュ)
2。なぜaopを研究するのか
*ソースコードを変更せずにプログラムを強化できます! ! (固定メソッドのプロキシを作成します。メソッドにアクセスする前に、最初にプロキシを入力します。プロキシでは、メソッドをより強力にしてプログラムを強化するために、より多くの関数を記述できます)
AOP:方向のプログラミング、すべてのモジュール化、各モジュールは比較的独立しており、モジュールは共有(同じ)でき、異なることは特にカスタマイズされます。従来の垂直プログラミングの代わりにこれを使用して、プログラムの再利用性を向上させる
3。AOP実装(実装原則)
AOPの実装には、クラスインターフェイスを実装するための2つのプロキシメソッド<1>が含まれています。
1. JDKダイナミックプロキシを実装します
1)永続レイヤーインターフェイス実装クラスを定義します
パッケージcom.clj.demo3; public interface userdao {public void save(); public void update();}パッケージcom.clj.demo3; public class userdaoimplはuserdao {@override public void save(){system.out.println( "save user"); } @Override public void update(){system.out.println( "user"を変更する "); }}2)JDKダイナミックプロキシツールクラスを定義します
このツールクラスは、Persistence Layer Saveメソッドを実行するときにいくつかの機能を追加し、開発中にソースコードを変更せずに特定の方法を強化する必要があります
パッケージcom.clj.demo3; import java.lang.lang.refllect.invocationhandler; import java.lang.refllect.method; import java.lang.lang.reflt.proxy;/** * jdkでプロキシオブジェクトを生成します(AOP原則を示す) * @author管理者 * getProxy(final userdao dao){//プロキシクラスを使用してプロキシオブジェクトを生成するuserdao proxy =(userdao)proxy.newproxyinstance(dao.getclass()。メソッドは、パブリックオブジェクトが呼び出されたら実行されます(オブジェクトプロキシ、オブジェクト[] arg)トランザクション} return method.invoke(dao、args)});プロキシを返します。 }}3)テスト
パッケージcom.clj.demo3; import org.junit.test; public class demo1 {@test public void run1(){//ターゲットオブジェクトuserdao dao = new userdaoimpl(); dao.save(); dao.update(); System.out.println( "===================================================================================================== ======================================================================================================================ツールクラスを使用して、userdao proxy = myproxyutils.getProxy(// proxy.update();2。CGLIBテクノロジーを実装します
1)永続レイヤーを定義する、現時点ではインターフェイスはありません
パッケージcom.clj.demo4; public class bookdaoimpl {public void save(){system.out.println( "save book"); } public void update(){system.out.println( "book"); }}2)書き込みツールのクラス
パッケージcom.clj.demo4; import java.lang.refllect.method; import org.springframework.cglib.proxy.enhancer; Import org.springframework.cglib.proxy.methodIntector; Import org.springframework.cglib.-proxy.methoxy; cglib proxy method * @author Administrator * */public class mycglibutils {/** * cglib method * @return *を使用してプロキシオブジェクトを生成 */public static bookdaoimpl getProxy(){Enhancer Enhancer = new Enhancer(); //親クラスEnhancer.setsuperclass(bookdaoimpl.class)を設定します。 // callback function enthancer.setcallback(new MethodEnterceptor(){@Override public object intercept(object obj、method method、object、[] objs、methodproxy methodproxy)スロー{if(method.getname()。実行 ");} methodproxy.invokesuper(obj、objs); //は、実行されたメソッド}}); //プロキシオブジェクトを生成bookdaoimpl proxy =(bookdaoimpl)enthancer.create();プロキシを返します。 }}3)テストクラスを作成します
パッケージcom.clj.demo4; import org.junit.test; public class demo1 {@test public void run1(){//ターゲットオブジェクトbookdaoimpl dao = new bookdaoimpl(); dao.save(); dao.update(); System.out.println( "==================================3。springのaspectj(構成ファイルメソッド)に基づくAOP開発
1)環境を展開し、対応するJARパッケージをインポートします
2)構成ファイルを作成し、AOPの制約を導入します
<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" xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd ">
3)インターフェイスを作成し、クラスを実装します
パッケージcom.clj.demo5; public interface customerdao {public void save(); public void update();}パッケージcom.clj.demo5;/** *構成ファイルを使用してAOP * @Author Administrator * */public Class customerdaoimplをcustomerdao {@override public void save(){// simulate exception // int a = 10/0; System.out.println( "customer save the Customer"); } @Override public void update(){// todo auto-enerated method stub.out.println( "customer"); }}4)ファセットクラスを定義します
パッケージcom.clj.demo5; import org.aspectj.lang.proceedjoinpoint;/** * facetクラス:エントリポイント +通知 * @author Administrator * */public class myaspectxml {/** *通知(特定の拡張)(特定の拡張) * */public void log(){system.out.out.out.out.outln( "log"); } / ** *メソッドが正常に実行されるか、例外が実行されます * / public void(){system.out.println( "final notification"); } /***メソッドが実行された後、ポスト通知が実行されます。プログラムで例外が発生した場合、投稿通知は実行されません */ public void afterreturn(){system.out.println( "post notification"); } / ** *メソッドが実行された後、例外がある場合、例外通知が実行されます} /***サラウンド通知:通知は、メソッドが実行される前後に行われます。 *デフォルトでは、ターゲットオブジェクトのメソッドを実行できず、ターゲットオブジェクトを手動で実行する必要があります */ public void(proceedingjoinpoint joinpoint){system.out.println( "wrap notification 1"); //ターゲットオブジェクトのメソッドを手動で実行するtry {joinpoint.proceed(); } catch(throwable e){// todo auto-enerated catch block e.printstacktrace(); } system.out.println( "wrap通知2"); }}5)実装クラスとファセットクラスを注入します
<?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" 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"> <!-- bean definitions here --> <!-- 配置客户的dao --> <bean id="customerDao"/> <!-- 编写切面类配置好--> <bean id="myAspectXml"/> <!-- 配置AOP --> <aop:config> <!-- 配置切面类:切入点+通知(类型)--> <aop:aspect ref="myAspectXml"> <!-- 配置前置通知,save方法执行之前,增强方法会执行--> <!-- 切入点表达式:execution(public void com.clj.demo5.CustomerDaoImpl.save()) --> <!-- 切入点表达式: 1.execution()固定的,必写2.public可以省略不写3.返回值必写,严格根据切入点方法而定,否则增强方法不会执行,可以用*代替,表示任意的返回值4.包名必写,可以用*代替(如:*..*(默认所有包); com.clj.*) 5.类名必写,可以部分用*(如*DaoImpl表示以'DaoImpl'结尾的持久层实现类),但不建议用*代替整个类名6.方法必写,可以部分用*(如save*表示以'save'开头的方法),但不建议用*代替整个类名7.方法参数根据实际方法而定,可以用'..'表示有0或者多个参数--> <!-- <aop:before method="log" pointcut="execution(public void com.clj.*.CustomerDaoImpl.save(..))"/> --> <aop:before method="log" pointcut="execution(* *..*.*DaoImpl.save*(..))"/> </aop:aspect> </aop:config></beans>
6)测试
package com.clj.demo5;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo1 { @Resource(name="customerDao") private CustomerDao customerDao; @Test public void run(){ customerDao.save(); customerDao.update(); }}扩展:切面类升级
<?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" 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"> <!-- bean definitions here --> <bean id="myAspectXml"/> <aop:config> <aop:aspect ref="myAspectXml"> <!-- 配置最终通知<aop:after method="after" pointcut="execution(* *..*.*DaoImpl.save*(..))"/>--> <!-- 配置后置通知<aop:after-returning method="afterReturn" pointcut="execution(* *..*.*DaoImpl.save*(..))"/>--> <!-- 配置异常通知<aop:after-throwing method="afterThrowing" pointcut="execution(* *..*.*DaoImpl.save*(..))"/>--> <aop:around method="around" pointcut="execution(* *..*.*DaoImpl.update*(..))"/> </aop:aspect> </aop:config></beans>
4、Spring框架AOP之注解方式
1)创建接口和实现类
package com.clj.demo1;public interface CustomerDao { public void save(); public void update();} package com.clj.demo1;public class CustomerDaoImpl implements CustomerDao{ @Override public void save() { // TODO Auto-generated method stub System.out.println("Save customer.."); } @Override public void update() { // TODO Auto-generated method stub System.out.println("Update customer"); }}2)定义切面类
package com.clj.demo1;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;/** * 注解方式的切面类* @Aspect表示定义为切面类*/@Aspectpublic class MyAspectAnno { //通知类型:@Before前置通知(切入点的表达式) @Before(value="execution(public * com.clj.demo1.CustomerDaoImpl.save())") public void log(){ System.out.println("记录日志。。"); } //引入切入点@After(value="MyAspectAnno.fun()") public void after(){ System.out.println("执行之后"); } @Around(value="MyAspectAnno.fun()") public void around(ProceedingJoinPoint joinPoint){ System.out.println("环绕通知1"); try { //让目标对象执行joinPoint.proceed(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("环绕通知2"); } //自定义切入点@Pointcut(value="execution(public * com.clj.demo1.CustomerDaoImpl.save())") public void fun(){ }}3)配置切面类和实现类,并开启自动代理
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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"> <!-- 开启自动注解代理--> <aop:aspectj-autoproxy/> <!-- 配置目标对象--> <bean id="customerDao"/> <!-- 配置切面类--> <bean id="myAspectAnno"/></beans>
spring提供了JDBC模板:JdbcTemplate类
1.快速搭建
1)部署环境
这里在原有的jar包基础上,还要添加关乎jdbc的jar包,这里使用的是mysql驱动
2)配置内置连接池,将连接数据库程序交给框架管理,并配置Jdbc模板类
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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"> <!-- 先配置连接池(内置) --> <bean id="dataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!-- 配置JDBC的模板类--> <bean id="jdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean></beans>
3)测试
package com.clj.demo2;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import javax.annotation.Resource;import org.apache.commons.dbcp.BasicDataSource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.cglib.beans.BeanMap;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/** * 测试JDBC的模板类,使用IOC的方式* @author Administrator * */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo2 { @Resource(name="jdbcTemplate") private JdbcTemplate jdbcTemplate; /** * 插入*/ @Test public void run1(){ String sql="insert into t_account values(null,?,?)"; jdbcTemplate.update(sql,"李钇林",10000); } /** * 更新*/ @Test public void run2(){ String sql="update t_account set name=? where id=?"; jdbcTemplate.update(sql,"李钇林",1); } /** * 删除*/ @Test public void run3(){ String sql="delete from t_account where id=?"; jdbcTemplate.update(sql,4); } /** * 测试查询,通过主键来查询一条记录*/ @Test public void run4(){ String sql="select * from t_account where id=?"; Account ac=jdbcTemplate.queryForObject(sql, new BeanMapper(),1); System.out.println(ac); } /** * 查询所有*/ @Test public void run5(){ String sql="select * from t_account"; List<Account> ac=jdbcTemplate.query(sql,new BeanMapper()); System.out.println(ac); }}/** * 定义内部类(手动封装数据(一行一行封装数据,用于查询所有) * @author Administrator * */class BeanMapper implements RowMapper<Account>{ @Override public Account mapRow(ResultSet rs, int rowNum) throws SQLException { Account ac=new Account(); ac.setId(rs.getInt("id")); ac.setName(rs.getString("name")); ac.setMoney(rs.getDouble("money")); return ac; } }2、配置开源连接池
一般现在企业都是用一些主流的连接池,如c3p0和dbcp
首先配置dbcp
1)导入dbcp依赖jar包
2)编写配置文件
<!-- 配置DBCP开源连接池--> <bean id="dataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean>
将模板类中引入的内置类datasource改为开源连接池的
3)编写测试类
配置c3p0
1)导入c3p0依赖jar包
2)配置c3p0
<!-- 配置C3P0开源连接池--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean>
将模板类中引入的内置类datasource改为开源连接池的
3)编写测试类
1、什么是事务
数据库事务(Database Transaction) ,是指作为单个逻辑工作单元执行的一系列操作,要么完全地执行,要么完全地不执行。 事务处理可以确保除非事务性单元内的所有操作都成功完成,否则不会永久更新面向数据的资源。通过将一组相关操作组合为一个要么全部成功要么全部失败的单元,可以简化错误恢复并使应用程序更加可靠。一个逻辑工作单元要成为事务,必须满足所谓的ACID(原子性、一致性、隔离性和持久性)属性。事务是数据库运行中的逻辑工作单位,由DBMS中的事务管理子系统负责事务的处理。
2、怎么解决事务安全性问题
读问题解决,设置数据库隔离级别;写问题解决可以使用悲观锁和乐观锁的方式解决
3、快速开发
方式一:调用模板类,将模板注入持久层
1)编写相对应的持久层和也外层,这里省略接口
package com.clj.demo3;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.support.JdbcDaoSupport;public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{ // Method 1: Inject the jdbc template class into the configuration file and write the template class private in the persistence layer JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void outMoney(String out, double money) { String sql="update t_account set money=money-? where name=?"; jdbcTemplate().update(sql,money,out); } public void inMoney(String in, double money) { String sql="update t_account set money=money+? where name=?"; jdbcTemplate().update(sql,money,in); }} package com.clj.demo4;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;public class AccountServiceImpl implements AccountService{ //It uses configuration file injection method, and the set method must be provided private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void pay(String out, String in, double money) { // TODO Auto-generated method stub accountDao.outMoney(out, money); int a=10/0; accountDao.inMoney(in, money); }}2)配置相对应的配置文件
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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"><!-- 配置C3P0开源连接池--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean><!-- 配置JDBC的模板类--> <bean id="jdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean><!-- 配置业务层和持久层--> <bean id="accountService"> <property name="accountDao" ref="accountDao"/> </bean><bean id="accountDao"> <!-- 注入模板类--> <property name="jdbcTemplate" ref="jdbcTemplate"/> <property name="dataSource" ref="dataSource"/> </bean></beans>
3)测试类
package com.clj.demo3;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo1 { @Resource(name="accountService") private AccountService accountService; @Test public void Demo1(){ //Call the payment method accountService.pay("Jia Xiansen","Li Yilin",100); }}方式二:持久层继承JdbcDaoSupport接口,此接口封装了模板类jdbcTemplate
1)编写配置文件
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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"> <!-- 配置C3P0开源连接池--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- 配置业务层和持久层--> <bean id="accountService"> <property name="accountDao" ref="accountDao"/> </bean> <bean id="accountDao"> <property name="dataSource" ref="dataSource"/> </bean></beans>
2)更改持久层
package com.clj.demo3;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.support.JdbcDaoSupport;public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{ //Method 1: Inject the jdbc template class into the configuration file and write the template class directly in the persistence layer// private JdbcTemplate jdbcTemplate;// public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {// this.jdbcTemplate = jdbcTemplate;// } // Method 2: The persistence layer inherits JdbcDaoSupport, which encloses the template class. The persistence layer of the configuration file does not need to inject the template class, nor does it need to configure the template class public void outMoney(String out, double money) { //jdbcTemplate.update(psc); String sql="update t_account set money=money-? where name=?"; this.getJdbcTemplate().update(sql,money,out); } public void inMoney(String in, double money) { String sql="update t_account set money=money+? where name=?"; this.getJdbcTemplate().update(sql,money,in); }}3)更改业务层
package com.clj.demo4;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;public class AccountServiceImpl implements AccountService{ //It uses configuration file injection method, and the set method must be provided private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void pay(String out, String in, double money) { // TODO Auto-generated method stub accountDao.outMoney(out, money); int a=10/0; accountDao.inMoney(in, money); }}4)测试类和上述一样
4、spring事务管理
In order to simplify transaction management code, Spring provides a template class TransactionTemplate, which can be manually programmed to manage transactions. You only need to use this template class! !
1、手动编程方式事务(了解原理)
1)快速部署,搭建配置文件,配置事务管理和事务管理模板,并在持久层注入事务管理模板
配置事务管理器
<!-- 配置平台事务管理器--> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean>
配置事务管理模板
<bean id="transactionTemplate"> <property name="transactionManager" ref="transactionManager"/></bean>
将管理模板注入业务层
<bean id="accountService"> <property name="accountDao" ref="accountDao"/> <property name="transactionTemplate" ref="transactionTemplate"/></bean>
全部代码:
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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"> <!-- 配置C3P0开源连接池--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- 配置业务层和持久层--> <bean id="accountService"> <property name="accountDao" ref="accountDao"/> <property name="transactionTemplate" ref="transactionTemplate"/> </bean> <bean id="accountDao"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置平台事务管理器--> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 手动编码方式,提供了模板类,使用该类管理事务比较简单--> <bean id="transactionTemplate"> <property name="transactionManager" ref="transactionManager"/> </bean></beans>
2)在业务层使用模板事务管理
package com.clj.demo3;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;public class AccountServiceImpl implements AccountService{ //Usage configuration file injection method, set method must be provided private AccountDao accountDao; //Inject transaction template class private TransactionTemplate transactionTemplate; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } /** * Method of transfer*/ public void pay(final String out,final String in, final double money) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { //The execution of the transaction, if there is no problem, submit, if Chu Xiang is exception, roll back protected void doInTransactionWithoutResult(TransactionStatus arg0) { // TODO Auto-generated method stub accountDao.outMoney(out, money); int a=10/0; accountDao.inMoney(in, money); } }); }}3)测试类和上一致
package com.clj.demo4;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext2.xml")public class Demo2 { @Resource(name="accountService") private AccountService accountService; @Test public void Demo1(){ //Call the payment method accountService.pay("Jia Xiansen","Li Yilin",100); }}申明式事务有两种方式:基于AspectJ的XML方式;基于AspectJ的注解方式
1、XML方式
1)配置配置文件
需要配置平台事务管理
<!-- 配置C3P0开源连接池--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- 配置平台事务管理器--> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean>
配置事务增强
<tx:advice id="myAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 给方法设置数据库属性(隔离级别,传播行为) --> <!--propagation事务隔离级别:一般采用默认形式:tx:method可以设置多个--> <tx:method name="pay" propagation="REQUIRED"/> </tx:attributes> </tx:advice>
aop切面类
<aop:config> <!-- aop:advisor,是spring框架提供的通知--> <aop:advisor advice-ref="myAdvice" pointcut="execution(public * com.clj.demo4.AccountServiceImpl.pay(..))"/> </aop:config>
全部代码
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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"> <!-- 配置C3P0开源连接池--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- 配置平台事务管理器--> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 申明式事务(采用XML文件的方式) --> <!-- 先配置通知--> <tx:advice id="myAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 给方法设置数据库属性(隔离级别,传播行为) --> <!--propagation事务隔离级别:一般采用默认形式:tx:method可以设置多个--> <tx:method name="pay" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- 配置AOP:如果是自己编写的AOP,使用aop:aspect配置,使用的是Spring框架提供的通知--> <aop:config> <!-- aop:advisor,是spring框架提供的通知--> <aop:advisor advice-ref="myAdvice" pointcut="execution(public * com.clj.demo4.AccountServiceImpl.pay(..))"/> </aop:config> <!-- 配置业务层和持久层--> <bean id="accountService"> <property name="accountDao" ref="accountDao"/> </bean> <bean id="accountDao"> <property name="dataSource" ref="dataSource"/> </bean></beans>
2)编写持久层和业务层(省略接口)
package com.clj.demo5;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.support.JdbcDaoSupport;public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{ //Method 1: Inject the jdbc template class into the configuration file and write the template class directly in the persistence layer// private JdbcTemplate jdbcTemplate;// public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {// this.jdbcTemplate = jdbcTemplate;// } // Method 2: The persistence layer inherits JdbcDaoSupport, which encloses the template class. The persistence layer of the configuration file does not need to inject the template class, nor does it need to configure the template class public void outMoney(String out, double money) { //jdbcTemplate.update(psc); String sql="update t_account set money=money-? where name=?"; this.getJdbcTemplate().update(sql,money,out); } public void inMoney(String in, double money) { String sql="update t_account set money=money+? where name=?"; this.getJdbcTemplate().update(sql,money,in); }} package com.clj.demo5;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.annotation.Transactional;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;public class AccountServiceImpl implements AccountService{ //It uses configuration file injection method, and the set method must be provided private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void pay(String out, String in, double money) { // TODO Auto-generated method stub accountDao.outMoney(out, money); int a=10/0; accountDao.inMoney(in, money); }}3)测试类
package com.clj.demo4;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext2.xml")public class Demo2 { @Resource(name="accountService") private AccountService accountService; @Test public void Demo1(){ //Call the payment method accountService.pay("Jia Xiansen","Li Yilin",100); }}2、注解方式
1)配置配置文件
配置事务管理
<bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean>
开启注释事务
<!-- 开启事务的注解--> <tx:annotation-driven transaction-manager="transactionManager"/>
全部代码
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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"> <!-- 配置C3P0开源连接池--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- 配置平台事务管理器--> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 开启事务的注解--> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 配置业务层和持久层--> <bean id="accountService"> <property name="accountDao" ref="accountDao"/> </bean> <bean id="accountDao"> <property name="dataSource" ref="dataSource"/> </bean></beans>
2)业务层增加@Transactional
package com.clj.demo5;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.annotation.Transactional;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;//Add this annotation in the current class means that all the current class has transactions @Transactionalpublic class AccountServiceImpl implements AccountService{ //Using configuration file injection method, the set method must be provided private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void pay(String out, String in, double money) { // TODO Auto-generated method stub accountDao.outMoney(out, money); int a=10/0; accountDao.inMoney(in, money); }}3)持久层不变
package com.clj.demo5;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.support.JdbcDaoSupport;public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{ //Method 1: Inject the jdbc template class into the configuration file and write the template class directly in the persistence layer// private JdbcTemplate jdbcTemplate;// public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {// this.jdbcTemplate = jdbcTemplate;// } // Method 2: The persistence layer inherits JdbcDaoSupport, which encloses the template class. The persistence layer of the configuration file does not need to inject the template class, nor does it need to configure the template class public void outMoney(String out, double money) { //jdbcTemplate.update(psc); String sql="update t_account set money=money-? where name=?"; this.getJdbcTemplate().update(sql,money,out); } public void inMoney(String in, double money) { String sql="update t_account set money=money+? where name=?"; this.getJdbcTemplate().update(sql,money,in); }}4)测试类
package com.clj.demo5;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext3.xml")public class Demo3 { @Resource(name="accountService") private AccountService accountService; @Test public void Demo1(){ //Call the payment method accountService.pay("Jia Xiansen","Li Yilin",100); }}上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。