오늘 저는 AOP를 계속 구현합니다. 나는 개인적으로 그것이 가장 유연하고 확장 가능한 방법이라고 생각합니다. 로그 관리를 예로 들어 Spring AOP 사용자 정의 주석 양식을 사용하여 로그 관리를 구현하십시오. 더 이상 고민하지 않고 즉시 시작하십시오! ! !
나는 구성에 대해 다시 말할 것이다.
ApplicationContext-mvc.xml에 추가해야합니다
<mvc : 주석 구동 /> <!-구성 요소 스캐닝 기능을 활성화하고, 패키지 com.gcx 및 그 하위 포장 아래에 주석을 통해 구성된 구성 요소를 자동으로 스캔합니다-> <context : component-scan base-package = "com.gcx" />-@aspectj 님이 @aspect jonnotation에 대한 시작 지원->-prox-target class e-class, the the the the the the the the the the the the the the the the the the the the the the the the 프록시-표적 클래스는 기본적으로 거짓입니다. 클래스가 인터페이스를 구현하면 JDK 프록시로 이동하십시오. 그렇지 않은 경우 CGLIB 프록시로 이동-> <!-참고 : 간단한 이익 모드에 CGLIB 프록시를 사용하는 것이 좋습니다. JDK Dynamic Proxy는 cglib 프록시보다 빠르지 만, 성능은 cglib-> <!만큼 좋지 않습니다.> <!-프록시-타겟 클래스 = "true"문장을 쓰지 않으면 문장이 괜찮습니다-> <aop : agage-autopproxy proxy-target class = "true"/> <!-<bean id = "systemlogaspect"> bean>.
다음으로 코드 작성을 시작하십시오.
로그 엔티티를 만듭니다
공개 클래스 SystemLog {개인 문자열 ID; 개인 문자열 설명; 개인 문자열 방법; 개인 긴 로그 타입; 개인 문자열 requestIP; 개인 문자열 ExceptionCode; 개인 문자열 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 (문자열 설명) {this.description = description == null? null : description.trim (); } public String getMethod () {return 메소드; } public void setMethod (문자열 메서드) {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 createate; } public void setCreatedate (날짜 createate) {this.createdate = createate; }}DAO 인터페이스 작성
package com.gcx.dao; import com.gcx.entity.systemlog; public Interface SystemLogMapper {int deleteByPrimaryKey (String ID); int insert (SystemLog 레코드); int insertSelection (SystemLog 레코드); SystemLog SelectByPrimaryKey (문자열 ID); int updateByPrimaryKey (SystemLog Record);}서비스 계층 작성
package com.gcx.service; import com.gcx.entity.systemlog; public Interface SystemLogService {int deletesystemlog (String id); int insert (SystemLog 레코드); int insertTest (SystemLog 레코드); SystemLog SelectSystemLog (String ID); int updateSystemLog (SystemLog Record);}서비스 구현 클래스 ServiceMpl을 작성하십시오
패키지 com.gcx.service.impl; import javax.annotation.resource; import org.springframework.stereotyp.service; import com.gcx.annotation.log; import com.gcx.dao.systemlogmapper; import com.gcx.entity.systemlog; 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.InserTselective (레코드); } @override public systemLog selectSystemLog (String id) {return SystemLogMapper.SelectByPrimaryKey (id); } @override public int updateSystemLog (SystemLog 레코드) {return SystemLogMapper.UpDateByPrimaryKeySelective (레코드); } @override public int insertTest (SystemLog 레코드) {return SystemLogMapper.Insert (레코드); }}여기서 기본 프로그램이 완료되었습니다
아래는 사용자 정의 주석입니다
package com.gcx.annotation; import java.lang.annotation.*; @target ({elementtype.parameter, elementtype.method}) @retention (retentionpolicy.runtime) @documented public @documented public @interface log { / ** 수행 할 작업 유형 : 예 : ADD OPERTION ** / PUBLIC STRINGTYPE () "; / ** 수행 할 특정 작업 (예 : 다음과 같이 수행 할 특정 작업).아래 컷을 작성하십시오
package com.gcx.annotation; import java.lang.reflect.method; import java.util.date; import java.util.uuid; import javax.annotation.resource; import javax.servlet.http.httpervletrequest; import javax.servlet.httpestession org.aspectj.lang.joinpoint; import org.aspectj.lang.proeessingjoinpoint; import org.aspectj.lang.annotation.after; import org.aspectj.lang.annotation.afterreturning; import org.aspectj.lang.annotation.afterthrowing; import org.asj.lang org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation.before; import org.aspectj.lang.annotation.annotation.annotation.pointcut; import org.slf4j.logger; import org.slf4j.loggeractory; import org.spramepramework.component; import; com.gcx.entity.systemlog; import com.gcx.entity.user; import com.gcx.service.systemlogservice; import com.gcx.util.jsonutil;/** * @author Yang Jian * @e-mail : email * @version 생성 시간 : 2015-19 4:29:05 PM * @DEC POM * @DEC. class*/ @agest @componentpublic class systemlogaspect {// 서비스를 주입하여 데이터베이스 @Resource에 로그를 저장합니다. @Resource // 나는 일반적으로 @autowired를 사용하여 자원 주석을 사용합니다. 그들의 차이. 시간이 있으면 후속 블로그에 개인 SystemLogService SystemLogService를 작성합니다. 개인 정적 최종 로거 로거 = loggerfactory.getLogger (SystemLogaspect. Class); // 컨트롤러 레이어 탄젠트 포인트 @PointCut ( "execution (* com.gcx.controller ..*.* (..))") public void controlleraspect () {}/*** pre-notification은 컨트롤러 계층을 가로 채기 위해 사용됩니다. System.out.println ( "========================================================================================================================= =================================================================== =================================================================== =================================================================== =================================================================== =================================================================== ====================================================================== System.out.println ( "============================================================================================== (ProceedingJoinPoint) .proceed (); System.out.println ( "================================================================================================= System.curentmillis ();) logger.info ( "Around" + joinpoint + " /tuse time :" + (END -START) + "MS는" + e.getMessage ())}}}}; httpervletrequest 요청 = (servletrequestattributes) getRequest Session (); = user.setId (1); class.forname (targetname); method.getAntation (log.class) .operationtype (); System.out.println ( " + jointpoint.getTarget (). getName () +". " + jointpoint.getSignature (). System.out.println ( " + IP); //*=============*// new SystemLog (); log.setMethod (j log.setexceptiondetail (null). } catch (예외 E) {// Local Exception Logger.Error ( "== Post-Notification Exception ="); System.out.println ( "====== 컨트롤러 실행 컨트롤러 실행 사후 회전 알림 ========); if (logger.isinfoEnabled ()) {logger.info ("afterEturn " + joinpoint);}} / ** * 예외 알림은 예외 * / @AfterThrowing * / @afterThering * / @AfterThering * / @AfterTHET * / @AFTERTOUT * / @AFTERTOUT * / @PARAM JOINGPOINT * / @param join "ControllerAspect ()", Throwing = "e") 공개 void doafterThrowing (joinpoint jointoint e) { /*httpservletrequest request = requestContexTholder.getRequestattributes (). SESTIONSTING.CURRENT_USTER는 IP 문자열 IP를 얻습니다 (jointoint.getArgs ()! = null && joinpoint.getArgs (). length> 0) {for (int i = 0; i <joinpoint.getArgs (). length; i ++) {joinpoint.getArgs () [i])}}}}}} getTarget (). getName (); if (method.getname (methodname)) {clazzs = method.getParameterTypes (clazzs.length == arguments.length) {getAntantation (log.class). /*============== Console Output ========* / System.out.println ( "============== 예외 알림 시작 ====================================================================================================================================== ========================================================================================================= ========================================================================================================= ========================================================================================================= System.out.println (예외 정보 : " + e.getMessage ());"예외 메소드 : " + (joinpoint.getTarget (). getName () +". system.out.println ( "requester :" + user.getname ()); log.SetId.RandomUuid (). log.setexceptionCode (getName ()); log SystemLogservice.insert (log); "============================================================= 로컬 예외 logger.error ("== 예외 예외 == "; ex.getMessage ();};}; e.getClass (). getName (), e.getClass (). getName (), params);나는 사전 통지, 서라운드 알림, 포스트 노 티스, 예외 알림 및 사후 통지를 포함하여 여기에 많은 글을 썼습니다. 실제 글에서 모든 것을 쓰지 않으면 괜찮습니다. 나는 포스트 로그에 로깅의 논리를 작성하는 데 익숙합니다. 프리 로그 알림 중 일부는 인터넷의 프리 로그 알림에도 포함되어 있지만 포스트 로그 알림에 작성하는 것이 좋습니다.
컨트롤러에 사용자 정의 주석을 추가하기 시작하겠습니다! !
package com.gcx.controller; import org.springframework.beans.bean.bean.annotation.autowired; import org.springframework.stereotyp.controller; import org.springframework.web.bind.annotation.requestmapping; import com.gcx.annotation.log; import com.gcx.service.userservice;@controller@requestmapping ( "usercontroller") 공개 클래스 usercontroller {@autowired private userervice userervice; @RequestMapping ( "testaop") @Log (OperationType = "Add Add :", OperationName = "Add user") public void testaop (문자열 사용자 이름, 문자열 암호) {userservice.adduser (username, password); }}아래 테스트 클래스를 작성하십시오
@Test public void testaop1 () {// 시작 스프링 컨테이너 시작 ApplicationContext CTX = new ClassPathXmlApplicationContext (새 문자열 [] { "classPath : ApplicationContext-mvc.xml", "classpath : ApplicationContext-datasource.xml"}); // 서비스 또는 컨트롤러 구성 요소 usercontroller usercontroller = (usercontroller) ctx.getbean ( "usercontroller"); usercontroller.testaop ( "zhangsan", "123456"); }데이터베이스 데이터 :
나는 원래 두 개의 탄젠트 포인트를 작성하고 싶었습니다. 하나는 서비스 계층이고 다른 하나는 컨트롤러 계층입니다. 서비스 계층은 예외 정보를 기록하는 데 사용되며 컨트롤러 계층은 기능을 기록하는 데 사용됩니다. 실행 결과는 다음과 같습니다.
이렇게하면 실제 프로젝트에서 운영 효율이 좋은지 모르겠습니다. 몇 가지 제안을하려면 여기 블로그의 Daniu를 참조하십시오! !
위의 예제 로그 관리를 구현하기위한 Spring AOP 사용자 정의 주석에 대한 설명은 내가 공유하는 모든 컨텐츠입니다. 나는 당신이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.