Baidu plus its own thinking , The following tests are effective , So write it down , It's also convenient for you to review, browse and deepen your impression , Any problems can be solved together with comments , Please correct the incompleteness , Progress together, ha ha
(1) First configuration file :

<!-- The statement is automatically spring Configuration in container @aspectj Tangential bean To create the agent , Weave into the section -->
<aop:aspectj-autoproxy />
<!-- Turn on annotation scanning -->
<context:component-scan base-package="com.ky.zhjd.**"/>
<!-- by true Indicates that the proxy is created based on the class ( Default false, Based on the interface is created ) -->
<aop:config proxy-target-class="true"></aop:config>

(2) Create a custom annotation class

Notice when you create Annotation, My name is ArchivesLog( The meaning of log file is ).

ArchivesLog.java Content :

package com.ky.zhjd.common.log;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* Custom annotation class
* @author ddz
*
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ArchivesLog { /** The type of operation to perform, such as : Add operation **/
public String operationType() default ""; /** The name of the operation to be performed, such as : Add a piece of user data **/
public String operationName() default ""; }

(3) Create a new section class , My name is LogAspect.java

package com.ky.zhjd.common.log;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; /**
* Section class
*
* @author ddz
*
*/
@Aspect
@Component("logAspect")
public class LogAspect { private static final Logger log = LoggerFactory.getLogger(LogAspect.class); // Configure weaving point
@Pointcut("@annotation(ArchivesLog)")
public void logPointCut() {
} /**
* Pre notice For interception operations , Execute... After the method returns
*
* @param joinPoint Tangent point
*/
@AfterReturning(pointcut = "logPointCut()")
public void doBefore(JoinPoint joinPoint) {
handleLog(joinPoint, null);
} /**
* Intercept abnormal operations , Execute when there is an exception
*
* @param joinPoint
* @param e
*/
@AfterThrowing(value = "logPointCut()", throwing = "e")
public void doAfter(JoinPoint joinPoint, Exception e) {
handleLog(joinPoint, e);
} private void handleLog(JoinPoint joinPoint, Exception e) {
try {
// Get annotations
ArchivesLog controllerLog = getAnnotationLog(joinPoint);
System.out.println("--------------- Custom annotation :" + controllerLog);
if (controllerLog == null) {
return;
}
// Get the method name
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
String type = controllerLog.operationType();
String name = controllerLog.operationName();
// Print log You can insert the database here
log.info(">>>>>>>>>>>>> Operation type :", type);
log.info(">>>>>>>>>>>>> Operation name :", name);
log.info(">>>>>>>>>>>>> Class name :", className);
log.info(">>>>>>>>>>>>> Method name :", methodName);
} catch (Exception exp) {
// Log local exception
log.error("== Pre notification exception ==");
log.error(" Abnormal information :", exp.getMessage());
exp.printStackTrace();
}
} /**
* Is there an annotation , If there is, get
*/
private static ArchivesLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null) {
// Get the information in the custom annotation
return method.getAnnotation(ArchivesLog.class);
}
return null;
}
}

(4) Use comments on methods , Then call the method

@ArchivesLog(operationType=" Query operation ",operationName=" Query a user's details ")
@RequestMapping(value = "/findByid", produces={"application/json;charset=UTF-8"})
public @ResponseBody BaseResult<Object> findByid(String id) {
String s="11";
BaseResult<Object> r=userService.findById(s);
System.out.println(r+">>>>>>>>>>");
return r; }

ok On the effect :

If there are any imperfections, please point out , Learning together

Use Spring Aop Custom annotation to achieve automatic logging of more related articles

  1. spring AOP User defined annotation to achieve log management

    Today we continue to achieve AOP, I think it's the most flexible here , Scalable way , Take log management for example , use Spring AOP User defined annotation form to realize log management . I don't say much nonsense , Just start !!! I'll say it again about configuration . stay appli ...

  2. spring AOP Custom annotation Realize log management

    Today we continue to achieve AOP, I think it's the most flexible here , Scalable way , Take log management for example , use Spring AOP User defined annotation form to realize log management . I don't say much nonsense , Just start !!! I'll say it again about configuration . stay appli ...

  3. utilize Spring AOP Custom annotation solves log and signature verification

    Reprint :http://www.cnblogs.com/shipengzhi/articles/2716004.html One . Problems to be solved part API There are signature parameters (signature),Passport First ...

  4. ( turn ) utilize Spring AOP Custom annotation solves log and signature verification

    One . Problems to be solved part API There are signature parameters (signature),Passport First, check the signature , The implementation method will only be executed if the verification is passed . The first implementation (Origin): Write verification code in the interface that needs signature verification , for example : ...

  5. Spring AOP User defined annotation realizes unified log management

    One .AOP Basic concepts of : AOP, Section oriented programming , Commonly used for logging , Business , Authority and other business processing .AOP yes OOP The continuation of , It is a hot topic in software development , It's also Spring An important part of the framework (Spring One of the core ), It's functional programming ...

  6. Spring aop+ Custom annotations uniformly log user behavior

    Write it at the front This article does not cover too much Spring aop Introduction to basic concepts and basic usage , Based on the actual scene use . scene We usually have such a need : Print the specific parameters of the background interface request , Print the final response result of the interface request , And record which user is in what ...

  7. Spring AOP Get custom annotation http Interface and WebService Interface input and output parameters

    The annotation method can be obtained in the following way :— Here is an example  HttpServletRequest request = ((ServletRequestAttributes) RequestContextHo ...

  8. SpringBoot series ( 13、 ... and ) Unified log processing ,logback+slf4j AOP+ Custom annotation , Walk up !

    Good recommendations from the past SpringBoot series ( One )idea newly build Springboot project SpringBoot series ( Two ) Introduction springBoot series ( 3、 ... and ) Configuration file details SpringBoot series ( Four )we ...

  9. spring aop Use annotation to summarize

    spring aop The way of annotation : and xml There is a slight difference in the configuration of , Detailed as follows : 1. First of all, we need to create the section class : Define the tangent point configuration in the aspect class , And all the notification methods that need to be implemented . /** * */ package com ...

Random recommendation

  1. Makefile Study &amp;binutils Toolset , Software development tools

    gcc -E Can effectively help us solve the macro related compilation errors : gcc -S Can get a C Source program file assembler : gcc -v Can get the path of the system header file Generate dependencies : gcc -M gcc -MM The build does not contain the system ...

  2. Nuget Version conflict problem

    There are two class library projects , One quoted, for example Newtonsoft.Json 6.0, The other cites, for example Newtonsoft.Json 8.0, And then the other exe The project references both class library projects . So when compiling, it will report w ...

  3. Linux Common commands :cd command

    ls The order is linux Give the most common command .ls The order is list Abbreviation  By default ls To print out a list of the current directory  If ls Specify a different directory  The list of files and folders in the specified directory will be displayed .  adopt ls  The command can not only view linu ...

  4. test post

    http://www.atool.org/httptest.php It can also be tested here There are plug-ins in Firefox :HttpRequester Chrome There are plug-ins :Postman

  5. CentOS6.5 System mount NTFS Partitioned mobile hard disk centos install repoforge Source (yum)

    CentOS6.5 System mount NTFS Partitioned mobile hard disk As IT The workers of , Can't avoid using Linux System , The system I'm using now is CentOS6.5 X86_64 Bit version , But insert NTFS There's no way to recognize it . Through the following ...

  6. POJ1502: MPI Maelstrom

    Red fruit dijstra Algorithm application , The adjacency table is used to store the graph episode :while(scanf("%d",&n)) Memory overrun on commit , Change to while(scanf("%d&quo ...

  7. How to be in Win10 Lower installation ubuntu Dual system

    Win10 Installation under system ubuntu System Preparation before installation : Concept Before you start , Be sure to understand the dual system first . System boot . This is 3 A concept , So you can understand the installation steps , Deal with unexpected situations during installation . Dual system Dual system is after power on , There will be a ...

  8. from 0 At the beginning Python Study 008 Variable

    local variable In the process of defining functions , There is no relationship between variables with the same name inside and outside the function . The name of the variable is local to the function , And the code block it's in is its scope . Use local variables # local variable def func(x): pr ...

  9. codeforces gym #102082C Emergency Evacuation( greedy Orz)

    Topic link : https://codeforces.com/gym/102082 The question : In a bus there are $r$ Row of seats , Each row of seats has $2s$ A seat , A corridor in the middle Yes $p$ I'm in the car , Find out the best way for everyone to get out of the bus ...

  10. turn :VB.NET Office Operation of the Word

    Here's a Word Operation of class , This class has the right to word The basic function of document operation , Include word Document creation , open , preservation , Save another , Insert a picture , Insert table , Insert text , Read text , Position the cursor , Move the cursor , Move to the specified page and so on ...