今日、私はAOPを実装し続けています。個人的には、それが最も柔軟で拡張可能な方法だと思います。 spring aopカスタムアノテーションフォームを使用して、ログ管理を実装するために、ログ管理を例に取ります。これ以上苦労せずに、すぐに始めましょう! ! !
構成についてもう一度言います。
ApplicationContext-mvc.xmlに追加するもの
<MVC:Annotation-driven /> <! - コンポーネントスキャン関数をアクティブ化し、パッケージcom.gcxおよびそのサブパッケージの下で注釈を介して構成されたコンポーネントスキャン関数を自動的にスキャンします - > <コンテキスト:コンポーネント-scanベースパッケージ= "com.gcx" /> <プロキシターゲットクラスはデフォルトでfalseです。クラスがインターフェイスを実装する場合は、JDKプロキシに移動します。そうでない場合は、CGLIB Proxyにアクセスしてください - > <! - 注:単純な利益モードにCGLIBプロキシを使用することをお勧めします。 JDKダイナミックプロキシはCGLIBプロキシよりも高速ですが、そのパフォーマンスはcglibほど良くありません - > <! - roxy-target-class = "true"を書いていない場合、文は大丈夫です - > <aop:aspectj-autopproxy proxy-target-class = "true"/> <!
次に、コードの書き込みを開始します。
ログエンティティを作成します
public class Systemlog {private string id;プライベート文字列の説明;プライベート文字列メソッド;プライベートロングログタイプ;プライベート文字列requestip;プライベート文字列例外コード。プライベート文字列ExceptionDetail;プライベート文字列パラメーション;プライベートストリングcreateby;プライベートデート作成型; public string getId(){return id; } public void setid(string id){this.id = id == null? null:id.trim(); } public string getDescription(){return description; } public void setDescription(string description){this.description = description == null? null:description.trim(); } public string getMethod(){return method; } public void setMethod(string method){this.method = method == null? null:method.trim(); } public long getLogType(){return logType; } public void setLogType(long logType){this.logtype = logType; } public string getRequestip(){return requestip; } public void setRequestip(string requestip){this.requestip = requestip == null? null:requestip.trim(); } public string getExceptionCode(){return ExceptionCode; } public void setExceptionCode(string exceptionCode){this.exceptionCode = exceptionCode == null? null:exceptioncode.trim(); } public string getExceptionDetail(){return ExceptionDetail; } public void setExceptionDetail(String ExceptionDetail){this.exceptionDetail = ExceptionDetail == null? null:exceptiondetail.trim(); } public string getParams(){return params; } public void setparams(string params){this.params = params == null? null:params.trim(); } public string getCreateby(){return createby; } public void setcreateby(string createby){this.createby = createby == null? null:createby.trim(); } public date getCreateDate(){return createdate; } public void setCreateDate(date recutedate){this.createdate = createdate; }}DAOインターフェイスを書く
パッケージcom.gcx.dao; import com.gcx.entity.systemlog; public interface systemlogmapper {int deletebyprimarykey(string id); int insert(systemlog record); Int InsertSelective(SystemLog Record); SystemLog SelectByPrimaryKey(String ID); int updatebyPrimaryKey(SystemLog Record);}サービスレイヤーの書き込み
パッケージcom.gcx.service;インポートcom.gcx.entity.systemlog; public interface systemlogservice {int deletesystemlog(string id); int insert(systemlog record); int insertTest(SystemLogレコード); SystemLog selectsystemlog(string id); int updateSystemLog(SystemLog Record);}Write Service実装クラスServiceImpl
パッケージcom.gcx.service.impl; import javax.annotation.resource; Import org.springframework.stereotype.service; Import com.gcx.annotation.log; Import com.gcx.dao.systemlogmapper; Import com.gcx.entity.systemlog; import; com.gcx.service.systemlogservice; @service( "SystemLogService")Public Class SystemLogServiceImpl SystemLogService {@Resource Private SystemLogMapper SystemLogMapper; @Override public int deletesystemlog(string id){return SystemLogMapper.DeleteByPrimaryKey(ID); } @Override public int insert(SystemLog Record){return SystemLogMapper.InsertSeective(record); } @Override public -SystemLog selectsystemlog(string id){return SystemLogMapper.SelectByPrimaryKey(ID); } @Override public int updatesSystemLog(SystemLog Record){return SystemLogMapper.updateByPrimaryKeySelective(record); } @Override public int insertTest(systemlog record){return systemlogmapper.insert(record); }}ここで、基本プログラムが終了しました
以下はカスタムアノテーションです
パッケージcom.gcx.annotation; import java.lang.annotation。*; @target({elementtype.parameter、elementtype.method})@retention(retentionPolicy.runtime)@documented public @interface log { / **実行される操作のタイプ:操作** / public String操作の追加/ **(ユーザーの追加**/ public String operationName()default "";}など、実行される特定の操作が実行されるべき操作が行われます。下にカットを書いてください
パッケージcom.gcx.annotation; import java.lang.refllect.method; import java.util.date; import java.util.uuid; import javax.annotation.resource; import javax.servlet.servlet.http.httpservletrequest; Import javax.http.httsession; org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import com.gcx.entity.systemlog; Import com.gcx.entity.user;インポートcom.gcx.serstylogservice;インポートcom.gcx.util.jsonutil;/** * @author yang jian * @email:email * @version作成時刻: class*/ @asted @componentpublic class systemlogaspect {// database @resourceにログを保存するためのインジェクションサービス//ここでは、一般的に @autowiredを使用してリソースアノテーションを使用します。それらの違い。時間があれば、後続のブログにprivate systemlogservice systemlogserviceを書きます。 private static final logger logger = loggerFactory.getLogger(SystemLogaspect。Class); //コントローラーレイヤーTangent Point @pointCut( "execution(* com.gcx.controller ..* System.out.println( "=========================================================================================================== =============================================================================== =============================================================================== =============================================================================== =============================================================================== =============================================================================== =============================================================================== System.out.println( "====================================================================================== (ProceedJoinPoint).ProCeed(); System.out.println( "=========================================================================================== logger.info( "abourd" + joinpoint + " /tuse time:" +(end -start) + "MS:" + e.getmessage()} /***ポスト通知は、ユーザーの操作を記録するためにコントローラー層を傍受するために使用されます* httpsertrequest request =((servletrequestattributes.getRequestattributes()) =新しいユーザーclass.forname(] methods.getmethods() ""; method.getAnnotation(log.class).operationtype(); system.out.println( "request method:" +(joinpoint.getTarget()。getname() + "。" + getname() + "()) +"。 system.out.println( "+============================ log.setMethod()。GetClass() + " log.setparams.setcreatedate(new date()); logger.error( "== notification xtion ==");コントローラー後の通知======= doafterthrowing(JoinPoint、Throwable e){ /*httpservletrequest request =((servletrequestattributes)requestcontextholder.getRequest() // request.getRemoteaddr(); Joinpoint.getargs()。長さ> 0){for(int i = 0; i <joinpoint.getargs() Joinpoint.getSignature(); method.getParametypes(); System.out.println( "==============例外通知Start ==================================================================================================================== ===================================================================================== ===================================================================================== ===================================================================================== System.out.println( "例外情報:" + e.getmessage()); System.out.println( " + user.getName()); out.println(" + ip); log.setid(uuid.randomuid()。 log.setmethod()。getname() + " + getsignature() +"() ") SystemLogService.Insert(log); ex.getMessage()); e.getClass()。getName()、e.getClass()。私はここで多くのことを書いています。これには、プレノティス、サラウンド通知、ポストノティス、例外通知、ミール後通知などがあります。私たちの実際の執筆ですべてを書かなければ大丈夫です。私はポストログにログインするロジックを書くことに慣れています。ログ前の通知の一部は、インターネット上のログ前通知にも含まれていることがわかりますが、ポストログ通知に記述する方が良いと感じています。
コントローラーにカスタム注釈を追加し始めましょう! !
パッケージcom.gcx.controller; Import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.controller; import org.springframework.web.bind.annotation.requestmapping; import com.gcx.annotation.log; import; com.gcx.service.userservice;@controller@requestmapping( "usercontroller")public class usercontroller {@autowired private userservice userservice; @RequestMapping( "testaop")@log(operationType = "add operation:"、operationname = "add user")public void testaop(string username、string password){userservice.adduser(username、password); }}以下にテストクラスを書きます
@test public void testaop1(){//スプリングコンテナApplicationContext ctx = new classpathxmlapplicationContext(new String [] {"classpath:applicationContext-mvc.xml"、 "classPath:ApplicationContext-DataSource.xml"}); //サービスまたはコントローラーコンポーネントusercontroller usercontroller =(usercontroller)ctx.getbean( "usercontroller"); USERCONTROLLER.TESTAOP( "Zhangsan"、 "123456"); }データベースデータ:
私はもともと2つの接線ポイントを書きたいと思っていました。1つはサービスレイヤーで、もう1つはコントローラーレイヤーです。サービスレイヤーは例外情報を記録するために使用されますが、コントローラーレイヤーは機能を記録するために使用されます。実行結果は次のとおりです。
これを行うと、実際のプロジェクトで運用効率が良いかどうかはわかりません。いくつかの提案をするために、こちらのブログのダニウをご覧ください! !
ログ管理を実装するためのSpring AOPカスタムアノテーション方法の上記の例は、私があなたと共有するすべてのコンテンツです。参照を提供できることを願っています。wulin.comをもっとサポートできることを願っています。