Spring AOP Learning Notes

Source: Internet
Author: User
Tags throwable

1. Configuring AOP through XML

1.1 Creating an AOP slice class

@Aspectpublic class Mkztaspect {private static final Logger log = Logmanager. GetLogger(Mkztaspect. Class);public void Mkztaround (Joinpoint point) {System. out. Print("starts execution of the module state slice.");Methodinvocationproceedingjoinpoint B = (methodinvocationproceedingjoinpoint) point;Object obj = b. Gettarget();object[] args = point. Getargs();String Pointstr = b. toString();String func = Pointstr. Substring(Pointstr. IndexOf("(") +1, Pointstr. IndexOf(")"));try {if ("Rwfxmkzt". Equals(func)) {list<map> mkztlist = mkjdgzutils. Getmkzt(args);if (mkztlist! = null && mkztlist. Size() >0) {Mkjdgzutils. Setmkzt(mkztlist);}} if ("SETMODULEMKZTBASEONCSLB". Equals(func)) {String LC = Stringutil. toString(args[0]);List<map> moduleids = (list<map>) args[1];Mkjdgzutils. SETMODULEMKZTBASEONCSLB(LC, Moduleids);} if ("Updatemkztbaseoncslxwhencstg". Equals(func)) {String CSLX = Stringutil. toString(args[0]);String ModuleID = Stringutil. toString(args[1]);Mkjdgzutils. Updatemkztbaseoncslxwhencstg(CSLX, ModuleID);} if ("UPDATEMKZTBASEONCSLXWHENCSBTG". Equals(func)) {String CSLX = Stringutil. toString(args[0]);String ModuleID = Stringutil. toString(args[1]);Mkjdgzutils. UPDATEMKZTBASEONCSLXWHENCSBTG(CSLX, ModuleID);} if ("Sbupdatemkzt". Equals(func)) {String Ddid = Stringutil. toString(args[0]);String Xmid = Stringutil. toString(args[1]);Mkjdgzutils. Sbupdatemkztsethistory(Ddid, Xmid);}} catch (Throwable e) {log. Error("module state Slice class execution method exception.");E. Printstacktrace();} try {b. Proceed();//methods of executing agents} catch (Throwable e) {E. Printstacktrace();}    }}
<?xml version= "1.0" encoding= "UTF-8"?><Beans xmlns="Http://www.springframework.org/schema/beans"    Xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"    XMLNS:AOP="HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"    Xmlns:tx="Http://www.springframework.org/schema/tx"    Xmlns:util="Http://www.springframework.org/schema/util"    xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring -aop-2.0.xsd Http://www.springframework.org/schema/tx Http://www.springframework.org/schema/tx/spring-tx-2.0.xs D http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd "    Default-autowire="ByName" Default-lazy-init="true">    <!--support @AspectJ tags --    <aop:aspectj-autoproxy />    <!--define AOP in ASPECTJ mode --    <!--test module status AOP --    <bean id= "mkztaspect" class=" Com.hnisi.scpt.gzl.mkjdgz.aop.MkztAspect ">    </Bean>    <aop:config proxy-target-class="true">        <!--to monitor multiple paths with | | Split -up        <aop:pointcut id="mkztupdate"expression="Execution (* com.hnisi.scpt.gzl.mkjdgz.service.mkztservice.* (..)) " />                    <aop:aspect id="Aopaspect" ref="Mkztaspect">            <!--module status update surround notification -            <aop:around pointcut-ref= "mkztupdate" method=" Mkztaround " />        </aop:aspect>    </aop:config></Beans>

Create a new Applicationcontext-aop.xml file with the contents of the configuration written under the Aop:config tab, where only one surround notification is configured Aop:around

1, first configure all the original object's beans.
2, then configure all the slice beans, configure the bean ID of the slice to map the slice class.
3, configuring AOP
(1) Configure tangency point: A notification that relates to which methods are executed when the relevant facets are called. The tangent is configured first, and a reference is kept for a while.
(2) Configure each facet:
A. Configures the mapping of the slice Bean's ID to the order plane priority, and the individual notifications within the slice.
B. Configures the mapping of notifications and pointcuts within individual facets, and the pointcut is given as a reference.
Aspect-oriented programming (AOP) compensates for the shortcomings of object-oriented programming (OOP) by providing another way to think about the structure of the program. The modular key unit in OOP is the class (classes), while the modular unit in AOP is the tangent plane. Facets enable modularity of concerns, such as cross-cutting of transaction management across multiple types and objects. (commonly referred to as crosscutting (crosscutting) concerns in AOP terminology.) )
The AOP framework is an important part of spring. But the spring IOC container does not rely on AOP, which means you have the right to choose whether to use AOP,AOP as a complement to the spring IOC container, making it a powerful middleware solution.
The Spring 2.0 AOP
Spring 2.0 allows users to choose to customize facets using simpler, more powerful pattern-based or @aspectj annotations. Both styles support the Pointcut language for all types of notifications (advice) and ASPECTJ, although they are still actually woven using spring AOP (Weaving).
This chapter discusses Spring 2.0 for schema-based and @aspectj-based AOP support. Spring 2.0 is completely backwards compatible with spring 1.2, and the next chapter discusses the underlying AOP support provided by the Spring 1.2 API.
The role of AOP in the spring framework
Provides declarative enterprise services, especially in lieu of EJB declarative services. The most important service is declarative transaction management.
Allows users to implement custom facets, using AOP to refine the use of OOP.
If you're only going to use a generic declarative service or a packaged declarative middleware service, such as a buffer pool (pooling), you don't have to deal directly with spring AOP, and much of this chapter can be skipped.
6.1.1. AOP Concepts
First let's start with some important AOP concepts and terminology. These terms are not unique to spring. But AOP terminology is not particularly intuitive, and if spring uses its own terminology, it will become even more confusing.
Facets (Aspect): A focus of modularity, which may be crosscutting across multiple objects. Transaction management is a good example of a crosscutting concern in the Java EE application. In spring AOP, facets can be implemented using pattern-based or @aspect annotations.
Connection point (Joinpoint): a particular point in the execution of a program, such as when a method is called or when an exception is handled. In spring AOP, a connection point always represents the execution of a method.
Notification (Advice): An action performed on a particular connection point on a slice. These include different types of notifications such as "Around", "before", and "after" (the type of notification will be discussed later). Many of the AOP frameworks, including spring, are notification models with interceptors, and maintain an interceptor chain centered on the connection point.
Pointcut (Pointcut): an assertion that matches a connection point. The notification is associated with a pointcut expression and runs on the connection point that satisfies the pointcut (for example, when a method for a particular name is executed). How Pointcut expressions match connection points is the core of AOP: Spring defaults to using the ASPECTJ pointcut syntax.
Introduced (Introduction): Used to declare additional methods or properties for a type (also known as a connection type declaration (Inter-type declaration)). Spring allows the introduction of new interfaces (and a corresponding implementation) to any Proxied object. For example, you can use ingestion to enable a bean to implement the IsModified interface to simplify the caching mechanism.
Target object: An object that is notified by one or more facets. Also called made informed (advised) objects. Since spring AOP is implemented by the runtime proxy, this object is always a proxy (proxied) object.
AOP Proxy: An object created by the AOP framework to implement a facet contract (such as notification method execution, and so on). In spring, an AOP proxy can be either a JDK dynamic agent or a cglib proxy.
Weaving (Weaving): Connects the facets to other application types or objects, and creates a notified object. These can be done at compile time (for example, with the AspectJ compiler), at class load time, and at run time. Spring, like other pure Java AOP frameworks, completes weaving at run time.
Notification Type:
Pre-notification (before advice): A notification that is executed before a connection point, but this notification does not block the execution process before the connection point (unless it throws an exception).
Post notification (after returning advice): A notification that is executed after a connection point is completed normally: for example, a method does not throw any exceptions and returns normally.
Exception notification (after throwing advice): A notification that is executed when a method throws an exception exits.
Final notification (after (finally) advice): A notification that is executed when a connection point exits (whether it is a normal return or an unexpected exit).
Surround notification (Around Advice): A notification that surrounds a connection point, such as a method call. This is the most powerful type of notification. Surround notifications can accomplish custom behavior before and after a method call. It also chooses whether to continue execution of the connection point or to return its own return value directly or throw an exception to end the execution.
Surround notifications are the most common types of notifications. Like ASPECTJ, Spring provides all types of notifications, and we recommend that you use the simplest possible notification type to achieve the functionality you need. For example, if you just need a return value for a method to update the cache, it's best to use a post-notification instead of a surround notification, although wrapping the notification can do the same thing. Using the most appropriate notification type can make the programming model simple and avoid many potential errors. For example, you do not need to invoke the proceed () method for wrapping notifications on Joinpoint, there is no problem with the call.
In spring 2.0, all the notification parameters are static types, so you can use the appropriate type (for example, the return value type after a method executes) as a parameter to the notification instead of using an object array.
The concept of matching connection points through Pointcuts is the key to AOP, which makes AOP different from other old technologies that simply provide interception capabilities. Pointcuts enable notifications to be independently mapped to object-oriented hierarchies. For example, a surround notification that provides declarative transaction management can be applied to a set of methods that span multiple objects, such as all business operations at the service layer.

Spring AOP Learning Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.