After the project has entered the integration testing phase, there is a problem when debugging:
When a bug occurs, the input and output are difficult to reproduce because of the complexity of the environment when the problem occurs.
This problem is a typical AOP application scenario.
With AOP, you can improve engineering efficiency in 2 ways:
1. Unified processing input, output log, decoupling parameters log module and specific business modules, to avoid writing a heap of logic in each method call to manually add the log code, the parameter log module changes without modifying the manually written log code, improve the overall system maintainability;
2. Ensure the consistency of log output format, easy to write automated tool analysis log, automatic alarm, improve system maintenance efficiency.
Aside from this: other scenarios that are suitable for using AOP can also be improved from the above 2 aspects of engineering efficiency.
Main code:
Interceptors:
Import Org.aopalliance.intercept.MethodInterceptor;
Import org.aopalliance.intercept.MethodInvocation;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
@Singleton
public class Inoutlogger implements Methodinterceptor {
Private final Logger Logger = Loggerfactory.getlogger (Inoutlogger.class);
Private Boolean isprint = true;
public Boolean getisprint () {
return inoutlogger.isprint;
}
public void Setisprint (Boolean isprint) {
Inoutlogger.isprint = Isprint;
}
@Override
Public Object Invoke (Methodinvocation mi) throws Throwable {
if (isprint) {
return this.invokewithlogging (MI);
} else {
return Mi.proceed ();
}
}
Private Object invokewithlogging (methodinvocation mi) throws Throwable {
Long startTime = System.currenttimemillis ();
Object obj = InvokeMethod (mi);
Logger.info ("InvokeMethod: {}, Elapsed time (ms): {}", Mi.getmethod (). GetName (), (System.currenttimemillis ()- StartTime));
object[] args = mi.getarguments ();
if (null! = args && args.length > 0) {
for (int i = 0; i < args.length; i++) {
Logger.info ("args[{}]: {}", I, args[i]);
}
}
Logger.info ("returns:{}", obj);
return obj;
}
}
Used to identify annotation that need to intercept the class:
@Retention (Retentionpolicy.runtime)
@Target (Elementtype.type)
Public @interface inoutlogging {
}
Use of interceptors:
Bindinterceptor (Matchers.annotatedwith (Inoutlogging.class), Matchers.any (), New Inoutlogger ());