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 does Spring AOP use pointcuts to create notifications

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "how Spring AOP uses pointcuts to create notifications". In daily operation, I believe many people have doubts about how Spring AOP uses pointcuts to create notifications. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about how Spring AOP uses pointcuts to create notifications. Next, please follow the editor to study!

I. what is the starting point

In the previous example, we can create a notification by creating a ProxyFactory, and then get the methods in the target class. You can do different things with these methods through different types of notifications. However, this approach works for all methods in the entire class, but most of the time we only want to notify some of the methods in this class, so we have to use pointcuts to precisely control specific methods.

In other words, our pointcut is used to determine the method in a class (accurate to the method), similar to defining some rules to find the class that matches this rule, which is much easier to read on.

II. Classification of cut-in points

In Spring, when you want to create a pointcut, you implement the Pointcut class.

Package org.springframework.aop;public interface Pointcut {ClassFilter getClassFilter (); MethodMatcher getMethodMacher ();}

The source code of the class returned by the above two methods is as follows:

ClassFilter

Package org.springframework.aop;/*** this is a functional interface, that is, pass in a class, * if the class meets our requirements, it returns true*, which means that the pointcut applies to the class (that is, the class does not match our rules) * / @ FunctionalInterfacepublic interface ClassFilter {boolean matches (Class var1);}

MethodMatcher

Package org.springframework.aop;import java.lang.reflect.Method;/***, of course, is used to match methods. * there are two types, dynamic and static, which is determined by the return value of isRuntime (). True is dynamic and false is static. This type determines whether the pointcut is dynamic or static * * / public interface MethodMatcher {MethodMatcher TRUE = TrueMethodMatcher.INSTANCE; / / for static matching, that is, it is independent of the parameters of the method boolean matches (Method var1, Class var2); boolean isRuntime (); / / for dynamic matching, that is, related to the parameters of the method, because the parameters are variable boolean matches (Method var1, Class var2, Object...). Var3);}

To sum up, there are two kinds of pointcuts, dynamic pointcuts and static pointcuts. Dynamic pointcuts check whether the arguments of the method meet the requirements each time, which will incur additional expenses. If possible, use static pointcuts whenever possible.

Third, the eight implementation classes of the pointcut describe the org.springframework.aop.support.annotation.AnnotationMatchingPointcut to find specific comments on the class or method, which requires a version of org.springframework.aop.aspectj.AspectJExpressionPointcut above JDK5 to use the AspectJ weaver to evaluate the pointcut declarative org.springframework.aop.support.ComposablePointcut using operations such as union () and intersection () to combine two or more pointcuts org.springframework.aop.support.ControlFlowPointcut is a special pointcut They match all the methods in the control flow of another method, that is, any method called directly or indirectly as a result of another method org.springframework.aop.support.JdkRegexpMethodPointcut the other method name uses regular expressions to define the pointcut, requiring org.springframework.aop.support.NameMatchMethodPointcut above JDK4 as the name implies This is a simple match to the list of method names, org.springframework.aop.support.DynamicMethodMatcherPointcut, which serves as the base class for creating dynamic pointcuts, org.springframework.aop.support.StaticMethodMatcherPointcut, as the base class for creating declaration pointcuts. 4. Use StaticMethodMatcherPointcut to create static pointcuts

Create a class and two methods. Our goal is to create a surround notification only in the walk () method and print the sentence, "I am a cute cat."

Public class Cat {public void sleep () {System.out.println ("sleep....");} public void walk () {System.out.println ("walking....");}}

Create a pointcut

Public class MethodPointcutDemo extends StaticMethodMatcherPointcut {@ Override public boolean matches (Method method, Class aClass) {return method.getName () .equals ("walk");} @ Override public ClassFilter getClassFilter () {return clz-> clz = = Cat.class / / the lambda expression above is equal to the following / / return new ClassFilter () {/ / @ Override// public boolean matches (Class clz) {/ / return clz = = Cat.class;//} / /};}

In the above method, of course, we don't have to implement the getClassFilter () method, because this method has already been implemented by the superior, so we can directly determine whether the class is Cat.class in the matches method.

Notification class (this is the same as last time, create a surround notification)

Import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;public class CatAdvisor implements MethodInterceptor {@ Override public Object invoke (MethodInvocation invocation) throws Throwable {/ / the most unreliable method, here we can determine whether the method is walk, so that we should notify System.out.println ("I am a cute Cat."); Object proceed = invocation.proceed (); return proceed;}}

Of course, we can also judge the method name and class name here, so why use the pointcut. But this is not reliable, we need to implement our logical code here, and it is more flexible to control which class and which method is notified through the pointcut.

Testing method

Public static void main (String [] args) {Cat cat = new Cat (); Pointcut pointcut = new MethodPointcutDemo (); / / pointcut instance Advice advice = new CatAdvisor (); / / Notification class instance (that is, the object of our notification code) Advisor advisor = new DefaultPointcutAdvisor (pointcut, advice); / / facet class, which is the collection of pointcut and notification classes ProxyFactory proxyFactory = new ProxyFactory () / / the difference between the previous code and the previous code is this sentence. Here we use pointcut control. If you comment on this sentence, you need to set the notification class proxyFactory.addAdvisor (advisor). / / set the facet class, including pointcut (control notification point) and notification class (logical code) / / if you comment the above sentence, use this sentence, all methods in this class will be notified / / proxyFactory.addAdvice (advice); / / set notification class proxyFactory.setTarget (cat); Cat proxy = (Cat) proxyFactory.getProxy (); proxy.sleep () Proxy.walk ();}

The result of the operation must be what we thought it was.

Sleep....I am a cute Cat.walking.... Use DyanmicMatcherPointcut to create dynamic pointcuts

This is the same as the static pointcut above, except that the notification is executed only if the parameters of the incoming method meet certain requirements. Because of the space, I will not write it, and I can understand it by downloading the code at the end of this article.

Sixth, other types of PointCut implementation class 1. Simple name matching (NameMatchMethodPointcut)

The target class and notification class are still the previous Cat class, and the implementation class of the previous pointcut does not need to be written, because this class has been implemented by default, and those who are interested can take a look at its source code. It is very simple to match the class name, similar to the static pointcut we just created.

Public class NameMatchPointcutDemo {public static void main (String [] args) {Cat cat = new Cat (); / / this class is already an implementation class, so we don't need to write the implementation class NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut (); pointcut.addMethodName ("walk"); Advisor advisor = new DefaultPointcutAdvisor (pointcut,new CatAdvisor ()); ProxyFactory proxyFactory = new ProxyFactory (); proxyFactory.addAdvisor (advisor) ProxyFactory.setTarget (cat); Cat proxy = (Cat) proxyFactory.getProxy (); proxy.sleep (); proxy.walk ();}} 2. Create a pointcut using regular expressions (JdkRegexpMethodPointcut)

Write only the test class, everything else is the same as above

Public class JdkRegexpPointcutDemo {public static void main (String [] args) {Cat cat = new Cat (); JdkRegexpMethodPointcut pointcut = new JdkRegexpMethodPointcut (); pointcut.setPattern (". * ee.*"); / / match sleep () Advisor advisor = new DefaultPointcutAdvisor (pointcut,new CatAdvisor ()); ProxyFactory proxyFactory = new ProxyFactory (); proxyFactory.addAdvisor (advisor); proxyFactory.setTarget (cat) Cat proxy = (Cat) proxyFactory.getProxy (); proxy.sleep (); proxy.walk ();}} 3. Create a pointcut using an AspectJ pointcut expression (AspectJExpressionPointcut)

Add related dependencies when using AspectJ

Org.aspectj aspectjrt 1.9.1 org.aspectj aspectjweaver 1.9.1 public class AspectJExpressionPointcutDemo {public static void main (String [] args) {Cat cat = new Cat (); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut (); pointcut.set_Expression ("execution (* walk* (..)"); Advisor advisor = new DefaultPointcutAdvisor (pointcut, new CatAdvisor ()); ProxyFactory proxyFactory = new ProxyFactory () ProxyFactory.addAdvisor (advisor); proxyFactory.setTarget (cat); Cat proxy = (Cat) proxyFactory.getProxy (); proxy.sleep (); proxy.walk ();}}

This execution expression means: any method that starts with walk and has any parameter and any return value

4. Create a pointcut for annotation matching (AnnotationMatchingPointcut)

First, customize a comment. If you don't understand it very well, refer to the custom annotation class in Java and apply it.

/ * * this annotation is used at run time, available for classes, and on methods * / @ Retention (RetentionPolicy.RUNTIME) @ Target ({ElementType.TYPE,ElementType.METHOD}) public @ interface MyAdvice {}

Then add this comment to the target method (the class to be notified)

/ * * in order not to conflict with the previous one, a new method * / @ MyAdvice public void eat () {System.out.println ("eating....");} is written.

Then specify the annotation name in the main method:

Public class AnnotationPointcutDemo {public static void main (String [] args) {Cat cat = new Cat (); AnnotationMatchingPointcut pointcut = AnnotationMatchingPointcut .forMethodAnnotation (MyAdvice.class); / / this class also has a .forClassAnnotation () method, that is, Advisor advisor = new DefaultPointcutAdvisor (pointcut, new CatAdvisor ()); ProxyFactory proxyFactory = new ProxyFactory (); proxyFactory.addAdvisor (advisor); proxyFactory.setTarget (cat) of the specified class. Cat proxy = (Cat) proxyFactory.getProxy (); proxy.sleep (); / will not be notified proxy.walk (); / / will not be notified proxy.eat (); / / will be notified}} this ends the study of "how Spring AOP uses pointcuts to create notifications", hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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