AOP I think everyone is very clear about. Sometimes we need to process some request logs, or monitor some methods, and what should be handled if there are exceptions? Now, we introduce AOP from spring-boot.
[Development environment: jdk version number is 1.8, spring
The version number of boot is 1.4.1]{style=”background-color:#FF0000”}
First, we will introduce the jar package first.
The POM file is added as follows:
<!--Cite AOP--><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId></dependency><!--Cite GSON, for printing--><dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.7</version></dependency>
After introducing the jar package, we add two simple request processing methods to boot startup:
@SpringBootApplication(scanBasePackages = {"com"})@RestControllerpublic class DemoApplication{ public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } //Test get request without parameters @RequestMapping(value = "/testAspect",method = RequestMethod.GET) public UserVo test(){ UserVo userVo = new UserVo(); userVo.setAge("23"); userVo.setName("He Xiaowu"); userVo.setSex("Male"); return userVo; } //Test the get request with parameters, let aop print the parameter content @RequestMapping(value = "/testAspectArgs",method = RequestMethod.GET) public UserVo test(String name,String age,String sex){ UserVo userVo = new UserVo(); userVo.setName(name); userVo.setAge(age); userVo.setSex(sex); return userVo; }After adding two simple request processing methods, let's add our aop
/** * Project name: SpringBootDemo * Creator: He Xiaowu* Creation time: 16/12/4 7:05 pm * Class name: AspectDemo * Class description: *///Declare is a section @Aspect//Declare is a spring managed bean@Component@Order(1)public class AspectDemo { private Logger log = Logger.getLogger(getClass()); private Gson gson = new Gson(); //Declare a point in the execution expression @Pointcut("execution(public * com.example.DemoApplication.*(..))") private void controllerAspect(){} //Print the content before requesting the method @Before(value = "controllerAspect()") public void methodBefore(JoinPoint joinPoint){ ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = requestAttributes.getRequest(); //Print the request content log.info("================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================= //Print the return content after the method is executed @AfterReturning(returning = "o",pointcut = "controllerAspect()") public void methodAfterReturning(Object o ){ log.info("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------After the two are configured, we request and then view the print log. First, start our container, and then we first request the parameterized processing method. The print log is as follows:
{width=”1232”
height=”132”}
It can be found that the requested url, method, args parameter values, types, and returned content are all printed out, indicating that this is the AOP intercept successfully.
Next, we test the request processing method without parameters, and print the log as follows:
{width=”1100”
height=”130”}
We can find that the method parameters printed in this method are an empty array because the method does not require parameter passing.
The above is springboot references aop for log processing of web processing. Here are some main annotations for AOP sections. The following are just descriptions and usage of the annotations. The author will not test them in detail. If you are interested, you can test them yourself:
Class annotation:
@Aspect defines a class as an aspect class
@order(i) marks the processing priority of the facet class. The smaller the i value, the higher the priority level. PS: You can annotate the class or annotate the method.
Method annotation:
@Pointcut defines a method as a point cut as an expression, the following details
@Before executes the method before the tangent point, the content is the specified tangent point
@After executes after point cut, before return,
@AfterReturning is executed after the entry point and return. If you want to process the return parameters of some methods, you can operate it here.
@Around surround the tangent point, execute before entering the tangent point, and after the tangent point
@AfterThrowing throws an exception after slit point for processing
@order(i) marks the priority of point cut. The smaller the i, the higher the priority
@Pointcut annotation combination:
In the above code, we define a tangent point that only processes the specified path:
@Pointcut("execution(public * com.example.DemoApplication.*(..))")private void controllerAspect(){}Now, we are defining a point tangent to handle other paths:
@Pointcut("execution(public * com.demo.*.*(..))")private void controllerDemo(){}The above tangent points are all processed separately. If we need a tangent point to process both of them, we can configure it like this:
@Pointcut(value = "controllerAspect()||controllerDemo()")private void all(){} In the @Pointcut annotation, directly refer to other method names annotated by @Pointcut, so that the point cut can handle the methods under two paths
@Pointcut annotation execution expression: public * com.demo.*.*(..)
The first public modifier representing method can use * instead of the first * to represent the return value, and * represents all
com.demo.* package path, .* represents the third package in the path.* represents the methods of all classes under all packages under the path.
(..) means unlimited method parameters
Some notes about @order(i) annotation:
The annotation class, the smaller the value, the higher the priority, the annotation method, the two annotations are annotated: @Before, the smaller the i value, the higher the priority, the higher the priority, the more annotated: @After or @AfterReturning, the larger the i value, the higher the priority.
To summarize the two, it is:
In the operation before the entry point, the operation after the entry point is performed by the order value from small to large, and the operation after the entry point is performed by the order value from large to small
extend:
Some readers may ask, if I want to print the time required for the request from the incoming and ending, define a member variable to count the time, and give @Before and @AfterReturning access, there may be synchronization problems. So we refer to a ThreadLocal object that specifies the generic type. The time of recording the request in @Before and deducting the record in @AfterReturning is the time consumed. The code is as follows:
/** * Project name: SpringBootDemo * Creator: He Xiaowu* Creation time: 16/12/4 7:05 pm * Class name: AspectDemo * Class description: *///Declaration is a section @Aspect//Declaration is a spring managed bean@Component@Order(1)public class AspectDemo { private Logger log = Logger.getLogger(getClass()); private Gson gson = new Gson(); ThreadLocal<Long> startTime = new ThreadLocal<Long>(); //Declare a point in the execution expression @Pointcut("execution(public * com.example.DemoApplication.*(..))") private void controllerAspect() { } //Print the content before requesting the method @Before(value = "controllerAspect()") public void methodBefore(JoinPoint joinPoint) { startTime.set(System.currentTimeMillis()); ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = requestAttributes.getRequest(); //Print the request content log.info("=========================================================================================================================================================================================================================================================================================================================================================================================================================================================================== Arrays.toString(joinPoint.getArgs())); log.info("========================================================================================================== Arrays.toString(joinPoint.getArgs())); log.info("Response content:" + gson.toJson(o)); log.info("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------The above are all the results obtained by my test. There may be differences or errors. Please correct me.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.