AOP face-to-face programming practice centralized unified login

Confucius said: review the old and learn the new. You can be a teacher. Analects of Confucius



I. concept

  • AOP is the abbreviation of Aspect Oriented Programming, which means: a technology to realize the unified maintenance of program functions through precompiling and runtime dynamic agent in Aspect Oriented Programming.


2, AspectJ

1. introduction:

  • The framework of face-to-face programming is an extension of Java, and it is fully compatible with Java. It defines the AOP syntax, has a special compiler to generate Class files complying with the Java bytecode encoding specification, and also supports native Java. It only needs to add the annotations provided by AspectJ.

2. terminology

  • Join point: points that are blocked.
  • PointCut: the definition of which joinpoints we want to intercept.
  • Advice: what needs to be done after the value intercepts the Joinpoint.
  • Introduction: a special notification without modifying class code.
  • Target: the target object of the agent.
  • Weaving: the process of applying enhancements to a target object to create a new proxy object.
  • Proxy: when a class is enhanced by AOP weaving, a result proxy class is generated.
  • Aspect: a combination of pointcuts and notifications.

3. practical exercises

1. Add dependencies to the root directory and the. gradle file of the project.
// 1. Root. gradle file
classpath 'org.aspectj:aspectjtools:1.9.4'
// 2. Project. gradle file
implementation 'org.aspectj:aspectjrt:1.9.4'

// 3. Add the following code at the end of the project. gradle file to print the log.
import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main

final def log = project.logger
final def variants = project.android.applicationVariants

//When building a project, edit
variants.all { variant ->
    if (!variant.buildType.isDebuggable()) {
        log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.")
        return;
    }

    JavaCompile javaCompile = variant.javaCompile
    javaCompile.doLast {
        String[] args = ["-showWeaveInfo",
                         "-1.9",
                         "-inpath", javaCompile.destinationDir.toString(),
                         "-aspectpath", javaCompile.classpath.asPath,
                         "-d", javaCompile.destinationDir.toString(),
                         "-classpath", javaCompile.classpath.asPath,
                         "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator)]
        log.debug "ajc args: " + Arrays.toString(args)

        MessageHandler handler = new MessageHandler(true);
        new Main().run(args, handler);
        for (IMessage message : handler.getMessages(null, true)) {
            switch (message.getKind()) {
                case IMessage.ABORT:
                case IMessage.ERROR:
                case IMessage.FAIL:
                    log.error message.message, message.thrown
                    break;
                case IMessage.WARNING:
                    log.warn message.message, message.thrown
                    break;
                case IMessage.INFO:
                    log.info message.message, message.thrown
                    break;
                case IMessage.DEBUG:
                    log.debug message.message, message.thrown
                    break;
            }
        }
    }
}

2. User defined notes
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
  String  value();
  int type();
}

3. Add a custom annotation to the method
 @MyAnnotation("Sign in")
    private void login() {
        Log.e("TAG", "Analog interface request Verification passed, login succeeded!");
    }

4. Write Aspect interface
@Aspect
public class `LoginAspect` {


    @Pointcut("execution(@com.kww.aopdmo.MyAnnotation) * * (..)")
    public void methodProduct(){

    }

    @Around("methodProduct()")
    public Object joinPoint(ProceedingJoinPoint joinPoint) throws Exception{
        Context context = (Context) joinPoint.getThis();
        if(true){// Generally, users' information, such as id, is obtained from SharedPreferences.
            Log.e("TAG", "Login detected!");
            try {
                return joinPoint.proceed();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }else {
            Log.e("TAG", "No login detected!");
            Toast.makeText(context, "Please log in first!", Toast.LENGTH_SHORT).show();
            context.startActivity(new Intent(context,LoginActivity.class));
            return null;
        }
        return null;
    }
}

5. Run the program and view the Log log
2020-03-15 17:32:10.165 12738-12738/com.kww.aopdmo E/TAG: analog interface request Verification passed, login succeeded!


Written at the end of the article

The paper must be light at last, and we must do it. Reading in winter night to show my son: Lu You

At this point, the use of enumeration in Java is finished, and you have a good time.


It's not easy to code. If this article helps you even a little, please don't be stingy with your praise. I will continue to bring more high-quality articles.

Published 15 original articles, won praise 17, visited 10000+
Private letter follow

Tags: Java Gradle Programming Android

Posted on Sun, 15 Mar 2020 08:19:47 -0400 by Brit