Фон требования
В недавнем проекте, когда проект в основном завершен, клиент предложил записать журналы всех бизнес -операций в базу данных и извлечь некоторую ключевую бизнес -информацию (например, номера заказа транзакций) в журнале.
Чтобы обеспечить период строительства, после просмотра информации я решил использовать AOP + пользовательские аннотации для выполнения этого требования.
Подготовка
Пакеты JAR, от которых необходимо зависеть для пользовательских аннотаций, включают AspectJrt-xxx.jar, AspectJweaver-xxx.jar и XXX, представляют номер версии.
Пользовательские аннотации
Отдельный пакет журналов создается в рамках проекта по хранению контента, связанного с журналом
**. Common.log.annotation // Место хранения на заказ **.
Создайте новый класс пользовательских аннотаций в пакете аннотаций:
пакет **. common.log.annotation; импорт java.lang.annotation.elementtype; импорт java.lang.annotation.retention; import java.lang.annotation.retentionpolicy; import java.lang.annotation.target; @Target ({elementType.method}@retentation Xxxoperatelog { / *** Тип операции Описание* @return* / string operateTypedesc () по умолчанию "; / *** Тип операции* @return*/ long OperateType () по умолчанию -1; / *** Модуль кодирование* @return*/ string mousecode () по умолчанию "M30"; / *** Имя модуля* @return*/ string mouseName () по умолчанию "xx module"; / *** Тип бизнеса* @return*/ string busstype () default ""; / *** Тип бизнеса Описание* @return*/ string busstypedesc () по умолчанию ";}Создайте новый XXXOperateLogaop в пакете AOP
Пакет **. common.log.aop; import **; // olmit @asment @componentpublic class xxxoperatelogaop {@autowired SystemLogService SystemLogService; Httpservletrequest request = null; Logger logger = loggerfactory.getLogger (xxxoPeratelogaop.class); Threadlocal <long> time = new Threadlocal <long> (); // Уникальный идентификатор, используемый для генерации журналов операций, используемый для вызова public static для журналов аудита бизнес -процессов Threadlocal <string> Tag = new Threadlocal <String> (); // Объявит точку входа AOP, любой метод, который использует xxxoperatelog, перехвачен @pointcut (" @annotation (**. Common.log.annotation.xxoperatelog)") public void log () {System.out.println ("I Am Arpty Point"); } / *** вырезать во всех местах, помеченных @log* @param joinpoint* / @before ("log ()") public void передэксек (joinpoint joinpoint) {time.set (system.currenttimemillis ()); Информация (JoinPoint); // Установить уникальное идентификационное число записей журнала tag.set (uuid.randomuuid (). ToString ()); request = ((ServletRequestattributes) requestContextholder.getRequestattributes ()). getRequest (); } @After ("log ()") public void phesleeexec (joinpoint joinpoint) {methodignature ms = (methodignature) joinpoint.getSignature (); Метод метод = ms.getmethod (); logger.debug ("Tag as" + Tag.get () + "Метод" + method.getName () + "Запуск потребления" + (System.currentTimeMillis () - time.get ()) + "ms"); } // В процессе выполнения целевого метода этот метод будет выполнен, и ведение журнала может быть реализовано здесь @Around ("log ()") public outeexec (ходатайство pjp) бросает Throwable {object ret = pjp.proceud (); try {object [] orgs = pjp.getargs (); SystemLog ValuerETURN = NULL; for (int i = 0; i <orgs.length; i ++) {if (orgs [i] exantyof systemlog) {valuereturn = (SystemLog) orgs [i]; }} if (valuereturn == null) {valuereturn = new SystemLog (); } if (valuereturn! = null && request! = null) {methodignature ms = (methodignature) pjp.getSignature (); Метод метод = ms.getmethod (); // Получить информацию журнала операции аннотации xxxoperatelog log = method.getannotation (xxxoperatelog.class); String businessType = log.busstype (); String BusinessDesc = log.busStypedESC (); Hashmap requestmap = servletutils.getparameterstohashmap (request); // ищите тип бизнеса по параметрам if (businesstype.equals ("")) {Object objbusinessType = requestMap.get ("business_type"); BusinessType = objbusinessType == null? "": objbusinessType.toString (); } // Нашел тип бизнеса из формы приложения для объекта результата выполнения Apply = request.getAttribute ("Apply"); if (Apply! = null) {jsonObject obj = jsonFactory.tojsonabstractentity (применить); if (obj! = null) {valuereturn.setotherDesc ("Применить номер:"+obj.getString ("Apply_no")); if (businesstype.equals ("")) {businesstype = obj.getString ("business_type"); }}} // Поиск типа бизнеса из параметров процесса выполнения метода (обычно вручную устанавливается) if (businesstype.equals ("")) {businesstype = (String) request.getattribute ("business_type"); BusinessType = BusinessType == null? "": BusinessType; } if (! BusinessType.equals ("") && businessDesc.equals ("")) {businessDesc = xxxsysConstant.business_type.getName (BusinessTipe); } valuereturn.setbusstype (xxxsysconstant.business_type.getNumber (BusinessType)); valuereturn.setBusStypeDesc (BusinessDesc); valuereturn.setmoudlecode (log.moudlecode ()); valuereturn.setmoudlename (log.moudlename ()); valuereturn.setoperateresult (xxxsysconstant.yesorno.yes); valuereturn.setoperatetype (log.operateType ()); valuereturn.setInputUserid ((((usercontext) webutils.getSessionAttribute (запрос, "xxxusercontext")). getsususer (). getId ()); valuereturn.setoperateTypedesc (log.operateTypeDesc ()); valuereturn.setRequestip (getRemotehost (запрос)); valuereturn.setrequesturl (request.getRequesturi ()); valuereturn.setserVerip (request.getlocaladdr ()); valuereturn.setuids (tag.get ()); // Сохранить операцию log SystemLogService.savesystemlog (ValuerETURN); } else {logger.info ("Не записывать информацию журнала"); } // Сохранить результат операции} catch (Exception e) {e.printStackTrace (); } return return; } // Записать журнал исключений @afterthroving (pointcut = "log ()", throwing = "e") public void doafterthroing (joinpoint joinpoint, throwable e) {try {info (joinpoint); Object [] orgs = joinPoint.getArgs (); SystemLog ValuerETURN = NULL; for (int i = 0; i <orgs.length; i ++) {if (orgs [i] exantyof systemlog) {valuereturn = (SystemLog) orgs [i]; }} if (valuereturn == null) {valuereturn = new SystemLog (); } if (valuereturn! = null && request! = null) {methodignature ms = (methodignature) joinpoint.getSignature (); Метод метод = ms.getmethod (); Xxxoperatelog log = method.getannotation (xxxoperatelog.class); String businessType = log.busstype (); String BusinessDesc = log.busStypedESC (); if (businesstype.equals ("")) {object objbusinesstype = servletutils.getparameterstohashmap (request) .get ("business_type"); BusinessType = objbusinessType == null? "": objbusinessType.toString (); BusinessDesc = xxxsysConstant.business_type.getName (BusinessType); } valuereturn.setbusstype (xxxsysconstant.business_type.getNumber (BusinessType)); valuereturn.setBusStypeDesc (BusinessDesc); valuereturn.setmoudlecode (log.moudlecode ()); valuereturn.setmoudlename (log.moudlename ()); valuereturn.setoperatetype (log.operateType ()); valuereturn.setoperateTypedesc (log.operateTypeDesc ()); valuereturn.setInputUserid ((((usercontext) webutils.getSessionAttribute (запрос, "xxxusercontext")). getsususer (). getId ()); valuereturn.setoperateresult (xxxsysconstant.yesorno.no); String errmes = e.getMessage (); if (errmes! = null && errmes.length ()> 800) {errmes = errmes.substring (0, 800); } valuerTurn.seterrormessage (errmes); valuereturn.setRequestip (getRemotehost (запрос)); valuereturn.setrequesturl (request.getRequesturi ()); valuereturn.setserVerip (request.getlocaladdr ()); valuereturn.setuids (tag.get ()); SystemLogService.SavesyStemLog (ValuerETURN); } else {logger.info ("Нет информации о журнале"); }} catch (Exception e1) {e1.printstacktrace (); }} private void info (joinpoint joinpoint) { logger.debug("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Object[] os = joinpoint.getargs (); joinpoint.getSignature ()); logger.debug ("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- request.getheader ("proxy-client-ip"); ip = request.getRemoteaddr ();Измените файл конфигурации Spring-Mvc.xml и добавьте следующую конфигурацию
<!-Включите перехват AOP-> <AOP: AspectJ-Autoproxy Proxy-Target-class = "true" /> <MVC: Annotation-управляемая /> <!-Определите область Spring Description Bean-> <Контекст: Component Scan Base-Package = "**. Common.log"> <Context-Filter Type = "Annotation". Express = "org.springframework.stereotype.controller"/> </context: component-scan>
Следует отметить, что вышеуказанная конфигурация должна быть размещена в одном и том же файле XML, либо Spring-Mvc.xml, либо Spring-context.xml, в противном случае он не может вступить в силу, и причина еще не была найдена.
Использование аннотаций
@Xxxoperatelog (busstype = xxxsysconstant.business_type.yyyy, busstypedesc = "Описание бизнеса", OperateType = xxxsysConstant.logoperateType.query, operatetypedesc = "Операция") @Requestmaping (value = "/**/**/QUERYSCX. = Requestmethod.post) public void Queryxxxxxx4datagrid (запрос httpservletrequest, httpservletresponse arg1, модель модели, писатель -писатель) { logger.info ("=================================================================================================== писатель) {logger.info ("=================================================================================================== писатель) {logger.info ("==================== httpservletresponse arg1, модель модели, писатель -писатель) {logger.info (" ================= logger.info ("==================== httpservletresponse arg1, модель модели, писатель -писатель) {logger.info (" ================ logger.info ("===================Приведенная выше аннотация SpringMVC, метод использования AOP для реализации ведения журнала - это все контент, которым я делюсь с вами. Я надеюсь, что вы можете дать вам ссылку, и я надеюсь, что вы сможете поддержать Wulin.com больше.