Latar Belakang Persyaratan
Dalam proyek baru -baru ini, ketika proyek pada dasarnya selesai, pelanggan mengusulkan untuk mencatat log dari semua operasi bisnis ke dalam database dan mengekstrak beberapa informasi bisnis utama (seperti nomor pesanan transaksi) di log.
Untuk memastikan periode konstruksi, setelah meninjau informasi, saya memutuskan untuk menggunakan anotasi khusus AOP + untuk menyelesaikan persyaratan ini.
Persiapan
Paket JAR yang perlu diandalkan untuk anotasi khusus termasuk aspekjrt-xxx.jar, aspekjweaver-xxx.jar, dan xxx mewakili nomor versi.
Anotasi khusus
Paket log terpisah dibuat di bawah proyek untuk menyimpan konten terkait log
**. Common.log.Annotation // Lokasi Penyimpanan Anotasi Kustom **. Common.log.aop // Lokasi Penyimpanan Alat AOP
Buat kelas anotasi kustom baru di bawah paket anotasi:
Paket **. Common.log.Annotation; import java.lang.annotation.elementType; import java.lang.annotation.retention; import java.lang.annotation.retentionPolicy; import java.lang.annotation.target; @target ({{{{{{{{{{{{{{{{{{{{elementypypy,)@target ({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{'method) Xxxoperatelog { / *** Jenis operasi Deskripsi* @return* / string operateTypeDesc () default ""; / *** Jenis Operasi* @return*/ Long OperateType () default -1; / *** Pengkodean modul* @return*/ string mouseCode () default "m30"; / *** Nama modul* @return*/ string mouseName () default "modul xx"; / *** jenis bisnis* @return*/ string busstype () default ""; / *** Jenis bisnis Deskripsi* @return*/ string busstypedesc () default "";}Buat xxxoperatelogaop baru di bawah paket AOP
Paket **. Common.log.aop; impor **; // omit @aspek @componentpublic kelas xxxoperatelogaop {@Autowired SystemLogService SystemLogService; Permintaan httpservletrequest = null; Logger logger = loggerFactory.getLogger (xxxoperatelogaop.class); Threadlocal <long> waktu = threadlocal baru <long> (); // ID unik yang digunakan untuk menghasilkan log operasi, digunakan untuk memanggil public static untuk proses audit proses bisnis threadlocal <string> tag = threadlocal baru <string> (); // Nyatakan titik masuk AOP, metode apa pun yang menggunakan xxxoperatelog dicegat @pointcut (" @annotation (**. Common.log.annotation.xxxoperatelog)") public void log () {System.out.println ("Saya adalah titik masuk"); } / *** Potong di semua tempat yang ditandai @log* @param goinpoint* / @before ("log ()") public void beforeexec (joinpoint joinpoint) {time.set (System.currentTimeMillis ()); info (goinpoint); // Atur nomor identifikasi unik dari tag catatan log.set (uuid.randomuuid (). Tostring ()); request = ((servletRequestAttributes) requestContextholder.getRequestAttributes ()). getRequest (); } @After ("log ()") public void afterexec (joinpoint joinpoint) {Methodyignature ms = (Methodyignature) joinpoint.getSignature (); Metode metode = ms.getMethod (); logger.debug ("Tag as" + tag.get () + "Method" + Method.getName () + "Jalankan konsumsi" + (System.currentTimeMillis () - time.get ()) + "ms"); } // Dalam proses pelaksanaan metode target, metode ini akan dieksekusi, dan logging dapat diimplementasikan di sini @around ("log ()") objek publik di sekitar EXExec (Prosidingjointpoint PJP) melempar Throwable {objek ret = pjp.proed (); coba {objek [] orgs = pjp.getArgs (); SystemLog valuereturn = null; untuk (int i = 0; i <orgs.length; i ++) {if (orgs [i] instance dari SystemLog) {valueReturn = (SystemLog) orgs [i]; }} if (valueReturn == null) {valueReturn = new SystemLog (); } if (valueReturn! = null && request! = null) {Methodyignature ms = (methodyignature) pjp.getSignature (); Metode metode = ms.getMethod (); // Dapatkan informasi log operasi dari anotasi xxxoperatelog log = method.getAnnotation (xxxoperatelog.class); String BusinessType = LOG.BUSSTYPE (); String BusinessDesc = LOG.BUSSTYPEDESC (); Hashmap requestMap = servletutils.getparameterstohashmap (permintaan); // Cari tipe bisnis dari parameter if (BusinessType.equals ("")) {objek objbusinessType = requestMap.get ("Business_Type"); BusinessType = objBusinessType == null? "": objbusinessType.tostring (); } // Menemukan jenis bisnis dari formulir aplikasi untuk objek hasil eksekusi berlaku = request.getAttribute ("apply"); if (apply! = null) {jsonObject obj = jsonfactory.toJsonAbstractentity (apply); if (obj! = null) {valueReturn.setotherdesc ("Apply Number:"+obj.getString ("apply_no")); if (BusinessType.Equals ("")) {BusinessType = obj.getString ("Business_Type"); }}} // Menemukan jenis bisnis dari parameter proses eksekusi metode (biasanya diatur secara manual) if (BusinessType.equals ("")) {BusinessType = (String) request.getAttribute ("Business_Type"); BusinessType = BusinessType == NULL? "": BusinessType; } if (! BusinessType.equals ("") && BusinessDesc.equals ("")) {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.setoperateresult (xxxsysconstant.yesorno.yes); valuereturn.setoperateType (log.operateType ()); valuereturn.setIncutUserId (((USerContext) webutils.getSessionAttribute (permintaan, "xxxusercontext")). getsysuser (). getid ()); valuereturn.setoperateTypeDesc (log.operatetypeDesc ()); valuereturn.setRequestip (getRemotehost (permintaan)); valuereturn.setRequesturl (request.getRequesturi ()); valuereturn.setserverip (request.getLocaladdr ()); valuereturn.setuids (tag.get ()); // Simpan Operasi Log SystemLogService.SavesyStemLog (Valuereturn); } else {logger.info ("Jangan merekam informasi log"); } // Simpan hasil operasi} catch (Exception e) {e.printstacktrace (); } return kembali; } // Rekam Log Pengecualian @AfterThrowing (pointcut = "log ()", throwing = "e") public void doafterthrowing (gabungan joinpoint, throwable e) {coba {info (goinpoint); Objek [] orgs = joinpoint.getArgs (); SystemLog valuereturn = null; untuk (int i = 0; i <orgs.length; i ++) {if (orgs [i] instance dari SystemLog) {valueReturn = (SystemLog) orgs [i]; }} if (valueReturn == null) {valueReturn = new SystemLog (); } if (valueReturn! = null && request! = null) {Methodyignature ms = (methodyignature) joinpoint.getSignature (); Metode metode = ms.getMethod (); Xxxoperatelog log = method.getAnnotation (xxxoperatelog.class); String BusinessType = LOG.BUSSTYPE (); String BusinessDesc = LOG.BUSSTYPEDESC (); if (BusinessType.equals ("")) {objek 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.setIncutUserId (((USerContext) webutils.getSessionAttribute (permintaan, "xxxusercontext")). getsysuser (). getid ()); valuereturn.setoperateresult (xxxsysconstant.yesorno.no); String errmes = e.getMessage (); if (errmes! = null && errmes.length ()> 800) {errmes = errmes.substring (0, 800); } valueReturn.seterrorMessage (errmes); valuereturn.setRequestip (getRemotehost (permintaan)); valuereturn.setRequesturl (request.getRequesturi ()); valuereturn.setserverip (request.getLocaladdr ()); valuereturn.setuids (tag.get ()); SystemLogService.Savesystemlog (Valuereturn); } else {logger.info ("Tidak ada informasi log yang direkam"); }} catch (Exception e1) {e1.printstacktrace (); }} info void pribadi (joinpoint goinpoint) { logger.debug("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Object[] os = joinpoint.getArgs (); Logger.debug ("Sourcelocation:/t" + joinpoint.getSourcelocation ()); Logger.debug ("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- request.getHeader ("Proxy-Client-IP"); request.getRemoteAddr ();} return ip.equals ("0: 0: 0: 0: 0: 0: 0: 0: 0: 0: 0: 0: 1")? "127.0.0.1"Ubah file konfigurasi spring-mvc.xml dan tambahkan konfigurasi berikut
<!-- Turn on AOP interception--> <aop:aspectj-autoproxy proxy-target-class="true" /> <mvc:annotation-driven /> <!-- Define the scope of Spring description Bean--> <context:component-scan base-package="**.common.log" > <context:include-filter type="annotation" Expression = "org.springframework.stereotype.controller"/> </konteks: component-scan>
Perlu dicatat bahwa konfigurasi di atas harus ditempatkan dalam file XML yang sama, baik spring-mvc.xml atau spring-context.xml, jika tidak mungkin tidak berlaku, dan alasannya belum ditemukan.
Penggunaan anotasi
@Xxxoperatelog (busstype = xxxsysconstant.business_type.yyyy, busstypeDesc = "deskripsi tipe bisnis", operateType = xxxsysconstant.logoperateType. RequestMethod.post) public void queryxxxxx4datagrid (permintaan httpservletrequest, httpservletresponse arg1, model model, penulis penulis) { Logger.info ("====================================================================================================================================================== penulis) {logger.info ("================================ HttpservletResponse arg1, model Model, penulis penulis) {Logger.info (" =========================================================================================================================== Logger.info ("===================== HTTPServletResponse arg1, model model, penulis penulis) {logger.info (" ============================================================================= Logger.info ("=================== HTTPServletResponse arg1, model model, penulis penulis) {logger.info (" ======================================================================================================= Logger.info ("===================== HTTPServletResponse Arg1, Model Model,Anotasi khusus SpringMVC di atas, metode menggunakan AOP untuk mewujudkan penebangan adalah semua konten yang saya bagikan dengan Anda. Saya harap Anda dapat memberi Anda referensi dan saya harap Anda dapat mendukung wulin.com lebih lanjut.