Detailed explanation of log4j and AOP in spring MVC project
preface
Log processing is a very important part of each project. Without logs, the controllability of the system will be lost. Without logs, there will be no trace of any problems in the system, which is very dangerous for an information system.
In the project, the calling process of class methods in the service needs to be logged with log4j.
There are many classes and methods in service, so it is impossible to add log4j logging function to each class separately. Therefore, we use the idea of AOP for horizontal section here.
Taking the method in the service class as the starting point, use log4j to output the log before and after the method call through AOP, including the class and method name being called.
In the process of configuration, the author encountered some problems in large or small details, which are recorded here.
First, we have two options for AOP configuration, one is through XML configuration, and the other is through annotation.
XML configuration can be through the following examples:
XML configuration
Then the corresponding aspect method does not need to use @ aspect, @ before and @ after annotations.
If the annotation method is used, only one line of configuration is required in the XML configuration file to enable the automatic agent function:
Automatic proxy
At this time, the corresponding aspect method can be as follows:
The second is the pit on the domain to which the spring configuration file belongs. If the AOP XML file configured here needs to be executed successfully, it needs to be
web. XML file. Add this XML configuration file to servlet context instead of spring context. An example is as follows:
The figure above shows configuring the global spring context, but the AOP configuration file cannot succeed here.
We need to load the AOP configuration in the servlet initialization context.
Finally, we run the project and use this method to view the AOP results:
summary
The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.