In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will give you a detailed explanation of what is AOP in Spring. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.
What is AOP?
AOP (Aspect Oriented Programming oriented aspect programming), a technology to realize the unified maintenance of program functions through pre-compilation and runtime dynamic agents. AOP is the continuation of OOP, is a hot spot in software development, is also an important content of Spring framework, and is a derivative paradigm of functional programming. Each part of the business logic can be isolated by using AOP, which reduces the coupling between the various parts of the business logic, improves the reusability of the program, and improves the efficiency of development at the same time.
Commonly used for logging, performance statistics, security control, transaction handling, exception handling, and so on.
Define AOP terminology
Aspect: an aspect is the modularization of a concern, which may be crosscutting multiple objects
Join Point: a join point is a specific point during the execution of a program, such as when a method is called or when an exception is handled
Advice: an action performed at a specific join point of a section. You can apply Notification 5 in Spring section:
Pre-notification (Before): notification executed before the target method or connection point is called; post-notification (After): notification executed after the completion of a connection point; return notification (After-returning): notification executed after the successful execution of a connection point; exception notification (After-throwing): notification executed after the method throws an exception Around: a method that surrounds a join point notification and executes custom methods before and after the notified method call.
Pointcut: an assertion that matches a join point. The notification is associated with a pointcut expression and runs on a join point that satisfies this pointcut, for example, when a method with a particular name is executed.
Introduction: an introduction, also known as an internal type declaration, declares additional methods or fields of a certain type.
Target object (Target Object): a target object is an object notified by one or more aspects.
AOP proxy (AOP Proxy): an AOP proxy is a pair object created by the AOP framework to implement faceted contracts (including functions such as notification methods)
Wearving: to connect a section to another application type or object and create an object that is notified. Or the process of forming a method of a proxy object.
Spring support for AOP
Agent-based classic SpringAOP; pure POJO section; @ AspectJ annotation-driven section; injection AspectJ section (applicable to all versions of Spring)
The first three are variants of SpringAOP implementations, and SpringAOP is built on dynamic proxies, so Spring's support for AOP is limited to method interception.
Pointcut expression
Use SpringAOP
SpringAOP support must be imported into spring-aspects 's jar package.
Org.springframework spring-aspects 4.3.5.RELEASE
Use annotations to define sections
Use annotations to define sections and notifications
@ Aspectpublic class Audience {/ / use the @ Pointcut annotation to declare the frequently used pointcut expression @ Pointcut ("execution (* com.wqh.concert.Performance.perform (..)") Public void performance () {} @ Before ("performance ()") public void silenceCellPhones () {System.out.println ("Sillencing cell phones");} @ Before ("performance ()") public void takeSeats () {System.out.println ("Task Seat");} @ AfterReturning ("performance ()") public void applause () {System.out.println ("CLAP CLAP CLAP");} @ AfterThrowing ("performance ()") public void demandRefund () {System.out.println ("Demand a Refund");}}
In addition, you need to add the configuration to the configuration file of applicationContext.xml, that is, spring:
Declare a section in XML
Define the pojo class. Here we just public class AudienceXML all the annotations defined above.
Public void silenceCellPhones () {System.out.println ("Sillencing cell phones");} public void takeSeats () {System.out.println ("Task Seat");} public void applause () {System.out.println ("CLAP CLAP CLAP");} public void demandRefund () {System.out.println ("Demand a Refund");}
ApplicationContext.xml configuration
Surround notification
There are five types of notifications in springAOP, and surround notifications are the most powerful notifications. It allows you to write logic that completely wraps the target method that is notified. In fact, it is like writing both pre-and post-notifications in a notification method. This article specifically explains the use of surround notices.
Use annotations
Define the section using the surround notification:
@ Aspectpublic class AudienceAround {/ / use the @ Pointcut annotation to declare the frequently used pointcut expression @ Pointcut ("execution (* com.wqh.concert.Performance.perform (..)") Public void performance () {} @ Around ("performance ()") public void watchPerformance (ProceedingJoinPoint joinPoint) {try {System.out.println ("Silencing cell phones"); System.out.println ("Taking seats"); joinPoint.proceed (); System.out.println ("Demanding a refund");} catch (Throwable throwable) {throwable.printStackTrace ();}
You can see that in the above code, the input parameter: ProceedingJoinPoint is added to the notification method when the notification is defined. This parameter must be written when creating a surround notification. Because you need to use the ProceedingJoinPoint.proceed () method in the notification to call the notified method.
In addition, if you forget to call the proceed () method, the notification actually blocks the call to the notified method.
Defined in XML
First, remove all the comments from the above class: here we recreate a class for the sake of distinction
Public class AudienceAroundXML {public void watchPerformance (ProceedingJoinPoint joinPoint) {try {System.out.println ("Silencing cell phones"); System.out.println ("Taking seats"); joinPoint.proceed (); System.out.println ("Demanding a refund");} catch (Throwable throwable) {throwable.printStackTrace ();}
Configuration:
Processing parameters in a notification
Spring uses AspectJ's tangent expression language to define Spring facets.
When trying to use other indicators in spring, an IllegalArgument-Exception exception is thrown.
Of these indicators, only the exception indicator actually performs the match, while the others are used to limit the match.
Section expression analysis
Tangent expression decomposition with parameters
The args (trackNumber) qualifier is used in this pointcut expression. The int type parameters that are passed to the playTrack () method are also passed to the notification. The parameter name trackNumber also matches the parameter in the pointcut method signature.
Create a section
@ Aspectpublic class TrackCounter {@ Pointcut ("execution (* com.wqh.aop.CompactDisc.playTrack (int)) & & args (trackNumber)") public void trackPlayder (int trackNumber) {} @ Before ("trackPlayder (trackNumber)") public void countTrack (int trackNumber) {System.out.println ("advance notice: targetNumber=" + trackNumber);}}
Connection point class
@ Servicepublic class CompactDisc {public void playTrack (int trackNumber) {System.out.println ("trackNumber =" + trackNumber);}}
XML configuration
test
@ Testpublic void testT () {ApplicationContext applicationContext = new ClassPathXmlApplicationContext (new String [] {"classpath:/spring/applicationContext.xml"}); CompactDisc compactDisc = (CompactDisc) applicationContext.getBean ("compactDisc"); compactDisc.playTrack (12);}
The parameter passed in to the specified method above is 12, which is obtained in the notification
In addition: configuring the aspect in xml to handle the parameters in the notification is similar, except that the pointcut expression is placed in the XML configuration file.
Add new functionality to the class
Introduce the knowledge of Spring in actual combat
In SpringAOP, we can introduce new methods for Bean. The proxy interceptor calls and delegates to other objects that implement the method.
When the method introducing the interface is called, the agent delegates the call to someone who implements the new interface to another object.
Use annotations to introduce
The code starts with the interface of the connection point and its implementation class
Public interface Person {void say ();}
Public class ChinesePerson implements Person {@ Override public void say () {System.out.println ("speak Chinese");}
Create the function that needs to be added, here the human extends the function of eating
Public interface Food {void eat ();}
Public class ChineseFood implements Food {@ Override public void eat () {System.out.println ("eat Chinese food");}
Write a section
@ Aspectpublic class addFuction {@ DeclareParents (value = "com.wqh.addfunction.Person+", defaultImpl = ChineseFood.class) public static Food food;}
Note that the expression here uses the @ DeclareParents annotation; the static attribute annotated indicates the interface to be introduced.
The value attribute used in the annotation specifies which type of bean to import into the interface, where the "+" sign after the Person indicates all subtypes, not the class itself. DefaultImpl, which specifies the class that provides the implementation for incoming functionality.
Use XML to configure bean:
test
@ Testpublic void testAdd () {ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("classpath:spring/applicationContext.xml"); Person person = (Person) applicationContext.getBean ("chinesePerson"); person.say (); / / chinesePerson bean can be converted to Food class here, so Food food = (Food) applicationContext.getBean ("chinesePerson"); food.eat ();}
Introduce in XML
First, delete all the above addFuction comments and leave the rest unchanged, and then add the appropriate configuration to the xml:
The types-matching here has the same function as the vale above.
Default-impl works the same as defaultImpl, and you can also use delegate-ref;. Of course, if you use delegate-ref, you have to refer to SpringBean.
Implement-interface is the interface to be introduced.
This is the end of this article on "what is AOP in Spring". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
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: 206
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.