The execution time of log-based printing method to achieve AOP

The execution time of log-based printing method to achieve AOP

1.Aop brief

Spring Framework AOP is thought aspect-oriented programming, using AOP called "cross" technique, the multi-functional business processes involve general extraction and individually packaged to form a separate section, at the right time these facets transverse cut business processes to the specified position (Baidu)

2. brief comment

I believe we use in daily development in many annotations, such as the common @Controller @Service @Autowired, etc., then up to you to define a note of it? Following is a brief introduction example:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Performance {
    String functionName() default "";
    String jobKey() default  "";
}

Annotation @Target illustrates the modified target range: Annotation may be used for packages, types (classes, interfaces, enumerations, Annotation type), a member type (method, constructor, member variables enumerated value), and the method parameters local variables (e.g., variable loop, catch parameters). Use a target in the Annotation type declaration can be more clear that modified target

@Retention press life cycle can be divided into three categories:
. 1, RetentionPolicy.SOURCE: There may be only retained in the source file, when compiled Java class file into a file, the annotation abandoned;
2, RetentionPolicy.CLASS: annotation to be retained class files, but jvm loading class files when they were abandoned, which is the default life cycle;
3, RetentionPolicy.RUNTIME: class notes not only be saved to a file and then load the jvm class files still exist;

@Documented notes indicate that this annotation tools javadoc should be recorded. By default, javadoc does not include annotations. However, if the statement notes specified @Documented, it will be treated like javadoc tool, also notes the type of information is included in the generated document, is a marker annotation, no members
(more than the concept of the author Baidu income, if you please point out the error)
and declare @interface type, which can define parameters examples have shown.
Notes itself also supports a number of other meta-annotation, Tell me what you are interested can find their own way about it, I was just in this simple application.

3.AOP specific code

@Aspect
@Component
public class PerformanceAspect {

    @Pointcut("@annotation(com.xx.xx.xx.Performance)")
    public void pointCut(){ }

    @Around("pointCut()")
    public void doBefore(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Performance annotation = signature.getMethod().getAnnotation(Performance.class);
        String functionName = annotation.functionName();
        if(functionName.isEmpty()){
            functionName = signature.getMethod().getName();
        }
        String jobKey = (String) AspectSupportUtils.getKeyValue(proceedingJoinPoint,annotation.jobKey());
        long start = System.currentTimeMillis();
        try {
             proceedingJoinPoint.proceed();
        }catch (Exception e){
             LogUtil.exception(e);
        }
        long end = System.currentTimeMillis();
        long timeUse = end - start;
        LogUtil.debug(" service :  " + functionName + jobKey+"  use time: "+timeUse+" ms");
    }

}

@Aspect declared as a class section

 @Pointcut("@annotation(com.znv.datacenter.annoations.Performance)")
    public void pointCut(){ }

@Pointcut annotation expression there are many support and implementation, are interested can Baidu, I am here on behalf of my comments where interception

The following main method

@Before: identify a pre-enhancement, which is equivalent BeforeAdvice functions.
@After: Final enhanced, whether it is throwing an exception or normal exit will be executed.
@AfterReturning: Rear enhanced, similar to AfterReturningAdvice, perform a method exits normally.
@AfterThrowing: enhanced exception is thrown, the equivalent of ThrowsAdvice.
@Around: surround enhancements, the equivalent of MethodInterceptor.

The logic is simple, get the method name, and then before and after the implementation of methods to intercept the timestamp of the last call log print.
Which of the following methods is to call the notes where itself.

 proceedingJoinPoint.proceed();

When used on a method to add comment

   @UseTemporaryDatabases
    @Performance(functionName = "database import operation job with jobkey : ", jobKey = "#jobKey")
    public void importData(List<Map> tableStructureList, String jobKey) throws Exception {
        DataSourceContextHolder.setDBType("temporarySource");
        //拼接数据库名的转义
        String tableName = "`" + jobKey + "`";
        dataCollectionMapper.importData(tableStructureList, tableName);
    }

Which should be noted is jobKey this parameter using the springEL expressions.
springEL expression is very strong, common @Value ( "$ {xxx}" ) is the use of a performance, but we own realization of the notes you want to use SpringEL expression, the need to add additional classes. Specifically refer to the following links: custom annotation support spring EL expressions .

Published an original article · won praise 0 · Views 3

Guess you like

Origin blog.csdn.net/qq_41696539/article/details/105047412