Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Spring method interceptor MethodInterceptor

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use the Spring method interceptor MethodInterceptor", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use the Spring method interceptor MethodInterceptor!

Preface to Spring method interceptor MethodInterceptor

By implementing the MethodInterceptor interface, when the method of the target object is called, it can be controlled before, during and after the method is called.

The MethodInterceptor interface can realize the functions that the MethodBeforeAdvice interface, the AfterReturningAdvice interface and the ThrowsAdvice interface can achieve, but the MethodInterceptor interface should be used carefully. It is likely that the call to the method of the target object will fail or fail to achieve the expected assumption because of a moment of negligence and forgetting the most important MethodInvocation.

The sample code is as follows

Public class TestMethodInterceptor {public static void main (String [] args) {ProxyFactory proxyFactory=new ProxyFactory (); proxyFactory.setTarget (new TestMethodInterceptor ()); proxyFactory.addAdvice (new adviseMethodInterceptor ()); Object proxy = proxyFactory.getProxy (); TestMethodInterceptor methodInterceptor = (TestMethodInterceptor) proxy; methodInterceptor.doSomeThing ("set proxy object through proxy factory, intercept proxy method") } public static class adviseMethodInterceptor implements MethodInterceptor {@ Override public Object invoke (MethodInvocation methodInvocation) throws Throwable {Object result=null; try {System.out.println ("before method execution:" + methodInvocation.getMethod () .toString ()); result= methodInvocation.proceed (); System.out.println ("after method execution:" + methodInvocation.getMethod () .toString ()) System.out.println ("method normal result:" + result); return result;} catch (Exception e) {System.out.println ("method exception:" + e.toString ()); System.out.println ("method run Exception result:" + result); return result } public String doSomeThing (String someThing) {/ / int iTunes 5Universe 0; return "execution blocked method:" + someThing;}}

Results of normal operation:

Before method execution: public java.lang.String com.blog.test.aop.TestMethodInterceptor.doSomeThing (java.lang.String)

After method execution: public java.lang.String com.blog.test.aop.TestMethodInterceptor.doSomeThing (java.lang.String)

Method normal operation result: execute the intercepted method: set the proxy object through the proxy factory, and intercept the proxy method

Abnormal operation result:

Before method execution: public java.lang.String com.blog.test.aop.TestMethodInterceptor.doSomeThing (java.lang.String)

Exception occurred in the method: java.lang.ArithmeticException: / by zero

Method to run Exception result: null

Spring interceptor implementation + background principle (MethodInterceptor) MethodInterceptor

MethodInterceptor is an interceptor in an AOP project, unlike a request when HandlerInterceptor intercepts a target, which intercepts a method.

Implementing MethodInterceptor interceptors can also be roughly divided into two types:

(1) MethodInterceptor interface

(2) using the annotation configuration of AspectJ

MethodInterceptor interface import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;public class MethodInvokeInterceptor implements MethodInterceptor {@ Override public Object invoke (MethodInvocation methodInvocation) throws Throwable {System.out.println ("before method invoke...."); Object object = methodInvocation.proceed (); System.out.println ("after method invoke."); return object;}}

Execute:

AspectJ's annotation import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.springframework.stereotype.Component;@Aspect@Componentpublic class AutoAspectJInterceptor {@ Around ("execution (* com.paic.phssp.springtest.controller..*.* (..)") Public Object around (ProceedingJoinPoint point) throws Throwable {System.out.println ("AutoAspectJInterceptor begin around."); Object object = point.proceed (); System.out.println ("AutoAspectJInterceptor end around."); return object;}}

Running result:

AutoAspectJInterceptor begin around.

>: isAuthenticated=false

AutoAspectJInterceptor end around.

Briefly introduce the key words.

AOP=Aspect Oriented Program programming for aspect (aspect / profile)

Advice (Notification): extract common business logic from each component as a separate component

Weave (weaving): the process of using an extracted component (Advice) to where the logic is needed.

JoinPoint (connection point): the Advice component can weave the feature points.

PointCut (pointcut): used to identify the join points that Advice needs to weave

Aspect (section): Aspect=Advice + PointCut

Notification Typ

@ Before executes before the pointcut method

@ After executes after the pointcut method

@ AfterReturning is executed when the pointcut method returns

@ AfterThrowing pointcut method throws exception execution

@ Around surround notification

Execution order:

@ Around surround notification

@ Before Notification execution

@ Before notifies the end of execution

@ Around surround notification execution ends

@ After post notification has been executed!

@ AfterReturning

Section Settin

You can use the & &, | |,!, and three operators to combine pointcut expressions

Execution expression "execution (public * com.xhx.springboot.controller.*.* (..)"

* only one path can be matched.

.. Can match multiple levels, can be a package path, or can match multiple parameters

+ can only be placed after the class, indicating that this class and all subclasses

Within (classpath) configures class instances of a specified type, and matches can also be used.

Within (com.xhx.springboot..*)

@ within (annotationType) matches the class with the specified annotation (note: different from above)

"@ within (org.springframework.stereotype.Component)"

@ annotation (annotationType) matches the method with the specified annotation

"@ annotation (IDataSource)"

Where: IDataSource is a custom annotation

Import java.lang.annotation.*;@Retention (RetentionPolicy.RUNTIME) @ Target ({ElementType.METHOD}) public @ interface IDataSource {String value () default "dataSource";} analyze Spring @ Aspect below

1. Registration

Org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator

When you see the implementation interface BeanPostProcessor, you must execute the interface method before and after initializing the Bean.

2. Analysis

AspectJAutoProxyBeanDefinitionParser.java#parse () method

@ Nullable public BeanDefinition parse (Element element, ParserContext parserContext) {AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary (parserContext, element); this.extendBeanDefinition (element, parserContext); return null;} public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary (ParserContext parserContext, Element sourceElement) {BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary (parserContext.getRegistry (), parserContext.extractSource (sourceElement)); useClassProxyingIfNecessary (parserContext.getRegistry (), sourceElement); registerComponentIfNecessary (beanDefinition, parserContext) @ Nullable public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary (BeanDefinitionRegistry registry, @ Nullable Object source) {return registerOrEscalateApcAsRequired (AnnotationAwareAspectJAutoProxyCreator.class, registry, source);}

3. Concrete realization

It is mentioned above that to implement the interface BeanPostProcessor, the interface method must be executed before and after initializing the Bean. Take a look at the following sequence diagram:

The postProcessAfterInitialization () method of AbstractAutoProxyCreator

The DefaultAopProxyFactory.createAopProxy () method, which specifically creates the proxy class. There are two kinds of dynamic agents: JDK dynamic agent and CGLIB agent.

Public AopProxy createAopProxy (AdvisedSupport config) throws AopConfigException {if (! config.isOptimize () & &! config.isProxyTargetClass () & &! this.hasNoUserSuppliedProxyInterfaces (config)) {return new JdkDynamicAopProxy (config);} else {Class targetClass = config.getTargetClass (); if (targetClass = = null) {throw new AopConfigException ("TargetSource cannot determine target class: Either an interface or a target is required for proxy creation.") } else {return (AopProxy) (! targetClass.isInterface () & &! Proxy.isProxyClass (targetClass)? New ObjenesisCglibAopProxy (config): new JdkDynamicAopProxy (config);} at this point, I believe you have a better understanding of "how to use the Spring method interceptor MethodInterceptor". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report