aspectj is an excellent aspect-oriented programming framework. Let’s briefly introduce the introductory tutorial:
1. Download AspectJ's jar package on the official website. I'm here with the latest version 1.8.7.
2. Because AspectJ.jar is an executable jar file, it needs to be run and installed.
Enter the directory where the jar is located and enter the command java -jar ***.jar:
3. Enter the installation:
4. When selecting next, there will be the following prompt. By default, select the jre installed on the computer:
5. Select next, and then select the installed directory. Remember the directory yourself, and it will be useful later:
6. After the installation is completed, there is a prompt to add aspectjrt.jar in lib to classpath;
Enter the installation directory, which contains the jar package library lib folder and the bin folder containing the runnable files:
Add aspectjrt.jar to add to classpath:
7. Perform a simple test of aspectj:
(1) Classes required to write tests: A, B and main class Main:
1 public class A 2 { 3 public void hello(){ 4 System.out.PRintln("Test the first instance first method"); 5 } 6 7 public void Hi(){ 8 System.out.println("Test the second method of the first instance"); 9 }10 11 } 1 public class B2 {3 public void greet(){4 System.out.println("The first method of the second class of test");5 }6 } 1 public class Main 2 { 3 public static void main(String[] args) 4 { 5 A a = new A(); 6 B b = new B(); 7 8 a.hello(); 9 a.Hi();10 11 b.greet();12 }13 }Check the effect of compilation execution:
(2) Write the aspect to add the target function to enter:
The first one:
1 public aspect AuthAspect 2 {3 before():execution(void *.*()){4 5 System.out.println("Simulation log");6 }7 }Use ajc in the bin folder to compile AuthAspect, -d. *.java to compile all java files in the current directory. Put the compiled files in the current directory:
The second one:
1 public aspect TransAspect 2 { 3 void around():execution(void *.*()){ 4 5 System.out.println("Simulate the beginning of things"); 6 7 procedure();//Callback function 8 9 System.out.println("Simulate the end of things");10 }11 }The third one:
1 public aspect LogAspect 2 {3 after():execution(void *.*()){4 5 System.out.println("******Simulation*******");6 }7 }