In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to use aspect programming AOP in the introduction of spring framework". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Dynamic agent
Features: bytecode is created on demand and loaded on demand
Function: enhance the method without modifying the source code
Classification:
Interface-based dynamic proxy based on subclass dynamic proxy involves classes ProxyEnhancer provider JDK official third party library cglib how to create a proxy object using the newProxyInstance method in Proxy using the create method in the Enhancer class requires the proxied class to implement at least one interface, without which the proxied object cannot be used as an interface-based dynamic proxy of the final class 1.1
The parameters of the newProxyInstance method:
ClassLoader: class loader. Used to load the proxy object bytecode, using the same class loader as the proxied class.
Written as: proxy object. GetClass (). GetClassLoader ()
Class []: bytecode array. Used to make the proxy object and the proxied object have the same method.
Written as: proxy object. GetClass (). GetInterfaces ()
InvocationHandler: code for enhancements. Write code to enhance the proxied method, generally write the implementation class of this interface, usually anonymous inner class, but not necessary, the implementation class of this interface is usually written by who uses it.
The invoke method in the InvocationHandler parameter through which any interface method of the proxied object executes. Method parameters and their meanings:
Proxy: reference to the proxy object
Method: the currently executed method
Args: parameters required for the current execution method
Return value: has the same return value as the proxied class
Code example:
Public class Client {public static void main (String [] args) {final ProducerImpl producer = new ProducerImpl (); producer.saleProduct (1000F); / / sell the product for 1000.0 System.out.println ("after enhancing the method.") Producer proxyProduct = (Producer) Proxy.newProxyInstance (producer.getClass () .getClassLoader (), producer.getClass () .getInterfaces () New InvocationHandler () {/ * executes any interface method of the proxied object through the method * the parameter meaning of the method * @ param proxy reference to the proxy object * @ param Method current execution method * @ param args the parameters required by the current execution method * @ return and the proxied object have the same return value * @ throws Throwable * / public Object invoke (Object proxy Method method, Object [] args) throws Throwable {/ / provides enhanced code Object returnValue = null / / 1. Get the execution parameter Float money = (Float) args [0]; / / 2. Determine whether the current method is the sales method if ("saleProduct" .equals (method.getName () {returnValue = method.invoke (producer, money * 0.8f);} return returnValue;}}); proxyProduct.saleProduct (1000F) / / sell the product and get the money 800.0} 1.2 dynamic agent based on subclass
The parameters of the create method:
Class: bytecode. Used to specify the bytecode of the delegated object.
Callback: used to provide enhanced code, similar to the invoke method of an interface-based dynamic proxy. Generally, it is written as the subinterface implementation class MethodInterceptor of this interface.
The method parameter of MethodInterceptor in the create parameter:
O: reference to the proxy object
Method: the currently executed method
Objects: parameters required for the current execution method
MethodProxy: the proxy object for the current execution method
Code example:
Public class Client {final Producer producer = new Producer (); public static void main (String [] args) {final Producer producer = new Producer (); producer.saleProduct (1000F); / / sell goods and get 1000.0 System.out.println ("after enhancing the method.") Producer cglibProducer = (Producer) Enhancer.create (producer.getClass () New MethodInterceptor () {/ * any method that executes any processed object will pass through the method * @ param o proxy object reference * @ param method current execution method * @ param objects the parameters required by the current execution method * @ param methodProxy proxy object for the current execution method * @ return * @ throws Throwable * / @ Override public Object intercept (Object o Method method, Object [] objects, MethodProxy methodProxy) throws Throwable {/ / provides an enhanced method Object returnValue = null / / 1. Get the execution parameter Float money = (Float) objects [0] of the current method; / / 2. Determine whether the current method is a sales action if ("saleProduct" .equals (method.getName () {returnValue = method.invoke (producer, money * 0.8f);} return returnValue;}}); cglibProducer.saleProduct (1000f) / / sell goods and get money 800.0}} 1.3 dynamic agent summary
General usage of dynamic agents:
Get the proxied class object (bytecode of the proxied object, class loader of the proxied class object, etc.)
Enhance the methods in the proxied class in the methods provided by the proxy class
2. AOP in spring
AOP in spring implements dynamic proxy through configuration.
2.1 related terms in spring:
* * Joinpoint (connection point): * * refers to the point that is intercepted. In spring, these points refer to methods, because spring only supports join points of method types. It can be understood as all the methods in the business layer.
* * Pointcut (pointcut): * * refers to the definition of which Joinpoint needs to be intercepted. It can be understood as an enhanced method.
* * Advice (Notification / Enhancement): * * refers to what needs to be done after intercepting Joinpoint. Notification types: pre-notification, post-notification, exception notification, final notification, surround notification.
Advance notification: notification prior to the execution of the business layer method
Post notification: notification after the execution of the business layer method
Exception notifications: notifications in catch
Final notifications: notifications in finally
Surround notification: the execution of the entire invoke method is surround notification
* * Introduction (introduction): * * A special notification that Introduction can dynamically add some methods or Field to the class at run time without modifying the class code.
Target (target object): the target object of the agent.
* * Weaving: * * refers to the process of applying enhancements to the target object to create a proxy object. Spring is dynamically weaved by proxy, while AspectJ uses compile-time weaving and class-loading weaving.
* * Proxy (proxy): * * when a class is enhanced by AOP weaving, a result proxy class is generated.
* * Aspect (aspect): * * is the combination of pointcut and notification (introduction).
2.2 AOP in spring
Development phase:
Write core business code (mainline development, familiar with business code for development)
Extract the common code and make it into a notification. (final stage of development)
Declare the relationship between pointcuts and notifications in the configuration file, that is, aspects.
Run phase:
The spring framework monitors the method execution of the pointcut. Once the monitoring pointcut method is run, the agent mechanism is used to dynamically create the proxy object of the target object, notify the category, weave the corresponding function of the notification in the corresponding position of the proxy object, and complete the complete code logic operation.
The AOP in spring will decide which dynamic proxy method to use based on whether the target implements the interface.
3. AOP configuration based on XML
3.1 leave notification classes to the IoC container to manage
Register the notification class in the IoC container of spring
3.2Using tags for AOP configuration
Used to declare aop configuration
3.3 use configuration section
Used to configure section
Attributes:
① id attribute: provides a unique identity for the section
The ② ref property: is the Id that specifies the notification class bean.
: used to configure advance notification
: used to configure post notification
Used to configure exception notification
: used to configure final notification
: used to configure surround notification
① method property: used to specify which method in the Logger class is the advance notification
② pointcut attribute: used to specify a pointcut expression that refers to which methods in the business layer are enhanced
③ pointcut-ref attribute: id that specifies the pointcut expression
3.4 use configuration pointcut expression
Used to configure pointcut expressions to specify which methods to enhance those classes
Attributes:
① id property: used to specify a unique identity of the pointcut
② expression attribute: used to configure pointcut expression
Code example:
4. Pointcut expression
Keywords: execution ("expression")
Expression writing: the access modifier returns the value package name. Name of the bag. Class name. Method name (parameter list)
Standard writing: public void cn.bruce.service.impl.AccountServiceImpl.saveAccount ()
The access modifier can be omitted (access permissions cannot be written *), indicating that it matches any type of access rights, but Spring now only supports public permissions.
Void cn.bruce.service.impl.AccountServiceImpl.saveAccount ()
The return value can use wildcards to indicate any return value.
* cn.bruce.service.impl.AccountServiceImpl.saveAccount ()
The package name can use wildcards to indicate any package, and several * should be written for the package at different levels.
*. AccountServiceImpl.saveAccount ()
The package name can be used. Represents the current package and its child packages
* cn..AccountServiceImpl.saveAccount ()
Both class and method names can be replaced by wildcards
* *. ()
* * Parameter list: * * write data types directly
Basic data types write names directly, such as int long double boolean
To reference a data type, write the full class name, such as cn.bruce.domain.Accout
You can use the wildcard character * to indicate any type, but you must have parameters
You can use the wildcard character * for placeholder, such as * *.. *. * (*, int)
You can use; use. Indicates whether there are parameters or not, and the parameters can be of any type *.
Full wildcard writing: * * (..)
Common ways to write pointcut expressions in development: for example, cut to all methods under the business layer implementation class * cn.bruce.service.impl.*.* (..)
5. Common notification types
Advance notification: executed before the pointcut method is executed
Post notification: executes after the pointcut method is executed. Post notification and exception notification can always be executed only one
Exception notification: executed after an exception occurs in the execution of the pointcut method. Exception notification and post notification can always be executed only one
Final notification: regardless of whether the pointcut method executes properly or not, it executes after it
Surround notification: the spring framework provides us with a way to manually control when the enhanced method is executed in the code.
Code example:
6. Annotation-based AOP configuration
Configuration steps:
① imports maven coordinates
Org.springframework spring-context 5.2.8.RELEASE org.aspectj aspectjweaver 1.9.6
② writes spring configuration class and enables package scanning and annotation support
@ configuration@ComponentScan ("cn.bruce") / / enable package scanning, configure packages to be scanned @ EnableAspectJAutoProxy (proxyTargetClass = true) / / enable annotation-driven public class SpringConfiguration {}
③ hands over the business layer entity classes to the IoC container management
@ Service ("testService") public class TestServiceImpl implements TestService {@ Override public void testOfVoid () {System.out.println ("testOfVoid is running.");} @ Override public void testOfInt (int I) {System.out.println ("testOfInt is running.number is" + I);} @ Override public void testOfInteger (Integer I) {/ / I = 1Comp0 System.out.println ("testOfInteger is running.number is" + I);} @ Override public void testOfAccount (Account account) {int I = 1 int 0; System.out.println ("testOfInt is running.number is" + account);}}
④ writes the aspect class, declares it as the aspect class, and sets the pointcut and notification type
@ Component ("logger") @ Aspect / / indicates that this class is the facet class public class Logger {@ Pointcut ("execution (* cn..impl.*.* (..)") / / specifies the pointcut expression private void pointcut () {} / * pre-notification * / @ Before ("execution (* cn..impl.*.* (int)") public void beforePrintLog () { System.out.println ("pre-notify the beforePrintLog method in the Logger class to start logging.") ;} / * Post Notification * / @ AfterReturning ("execution (* cn..impl.*.* (Integer)") public void afterReturningPrintLog () {System.out.println ("Post Notification afterReturningPrintLog method in the Logger class starts logging.") ;} / * exception notification * / @ AfterThrowing ("pointcut ()") public void afterThrowingPrintLog () {System.out.println ("exception notifies the afterThrowingPrintLog method in the Logger class to start logging.") ;} / * final notification * / @ After ("execution (* cn..impl.*.* ())") public void afterPrintLog () {System.out.println ("finally notify the afterPrintLog method in the Logger class to start logging.") ;} / * surround notification * / @ Around ("execution (* cn..impl.*.* (cn.bruce.domain.Account)") public Object aroundPringLog (ProceedingJoinPoint pjp) {Object rtValue = null; try {/ / get the parameter Object [] args = pjp.getArgs () required for method execution System.out.println ("the aroundPringLog method in the Logger class starts logging." ); / / explicitly call the business layer method (pointcut method) rtValue = pjp.proceed (args); System.out.println ("the aroundPringLog method in the Logger class starts logging." Return rtValue;} catch (Throwable t) {System.out.println (the aroundPringLog method in the Logger class starts logging. Exception "); throw new RuntimeException (t);} finally {System.out.println (" the aroundPringLog method in the Logger class starts logging. " Finally ");}
⑤ writing test class for testing
Public class TestAOP {public static void main (String [] args) {ApplicationContext ac = new AnnotationConfigApplicationContext (SpringConfiguration.class); TestService testService = (TestService) ac.getBean ("testService"); testService.testOfInt; System.out.println ("-"); testService.testOfInteger ("-"); System.out.println ("-") TestService.testOfVoid (); System.out.println ("-"); Account account = (Account) ac.getBean ("account"); account.setName ("Bruce"); account.setAge (11212); testService.testOfAccount (account);}} "introduction to spring Framework how to use aspect programming AOP" ends here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
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.