Spring's AOP II

Source: Internet
Author: User
Tags throwable

Using dynamic proxies to inject log printing into target objects in the spring AOP one is actually the principle of AOP implementation, but this is just the way Java is implemented. AOP no matter what language it's a few key concepts still need to understand.

First, the concept of AOP

1. Crosscutting concerns

AOP divides a business process into several parts, such as permission checking, business processing, logging, each part being processed separately, and then assembling them into a complete business flow, each of which is called a tangent or a point of focus.

2. Facets

A class is an abstraction of an object's characteristics, and a facet is an abstraction of a crosscutting concern. Each part can be abstracted into a stack of paper as one layer, and every piece of paper is all sides.

3. Connection Points

Intercepted points, I see some blog said: Because spring only supports the method type of connection point, so in spring the connection point refers to the method is intercepted, in fact, the connection point can also be a field or a constructor. Actually, I think spring only supports connection points for method types that contain fields and constructors. Why is it? Because the field it is through the Get,set method, the constructor is actually also a method. Spring only supports connection points for method types and connection points are fields or constructors they are containment relationships.

4. Entry point

The connection point to intercept the definition, the connection point can be many, but not necessarily each connection point to operate, such as Lotus Root, Lotus root and the lotus segment between them are connected points, but not necessarily all cut.

5. Notice

Notice refers to the interception to the connection point after the code to execute, the notification is divided into pre-, post-, exception, final, surround notification of five categories, this is the Lotus root and the Lotus root segment after the thing to do, is to add honey or do what.

6. Target Object

The target object of the agent is the goal of the dynamic agent of the previous blog, in which the interface of AOP is implemented in practice, and then the objects that are applied are configured, and the object is the target object.

7. Weave into

The aspect is independent, the target object is also independent, they are not coupled, then how does it put the slice into the target object, then need to weave into the operation, just like one, how to put the target and print logs together, then need dynamic agent, In spring, aop.framework.ProxyFactory is used as a loom for cross-cutting logic weaving.

8. Introduction

Add methods or fields dynamically for the class without changing the code.

Second, AOP configuration

AOP configuration Elements Description
<aop:config> The top-level AOP configuration element, where most <aop:*> elements must be contained <aop:config> within the element
<aop:aspect> Defining facets
<aop:aspect-autoproxy> Enable @aspectj annotation-driven facets
<aop:pointcut> Defining pointcuts
<aop:advisor> Defining an AOP Notifier
<aop:before> Defining AOP Pre-notifications
<aop:after> Define an AOP post notification (regardless of whether the method being notified succeeds)
<aop:after-returning> To define a notification after a successful return
<aop:after-throwing> To define a notification after an exception is thrown
<aop:around> Defining AOP Surround Notifications
<aop:declare-parents> Introduces an additional interface to the notified object and transparently implements the

Third, the realization

1.pom.xml introduced Aspectjweaver.jar, Aspectjrt.jar

<dependency>    <groupId>aspectj</groupId>    <artifactid>aspectjweaver</ artifactid>    <version>1.5.4</version></dependency>    <!--https://  MVNREPOSITORY.COM/ARTIFACT/ASPECTJ/ASPECTJRT-<dependency>    <groupid>aspectj</ groupid>    <artifactId>aspectjrt</artifactId>    <version>1.5.4</version></ Dependency>
View Code

2. Defining Slice Classes

 PackageCuiyw.Spring.Service;ImportOrg.aspectj.lang.JoinPoint;ImportOrg.aspectj.lang.ProceedingJoinPoint; Public classServiceaspect { Public voidBeforeadvice () {System.out.println ("The pre-notification was executed"); }     Public voidAfteradvice () {System.out.println ("The post notification was executed."); }     Public voidAfterreturnadvice (String result) {System.out.println ("Return notification executed" + "run business method returned result of" +result); }     PublicString Aroundadvice (Proceedingjoinpoint proceedingjoinpoint)throwsthrowable {String result= ""; Try{System.out.println ("Surround notification starts executing."); LongStart =System.currenttimemillis (); Result=(String) proceedingjoinpoint.proceed (); LongEnd =System.currenttimemillis (); System.out.println ("Surround notification execution is over"); System.out.println ("Execution Business Method Total:" + (End-start) + "milliseconds." "); } Catch(Throwable e) {}returnresult; }     Public voidThrowingadvice (Joinpoint joinpoint, Exception e) {stringbuffer StringBuffer=NewStringBuffer (); Stringbuffer.append ("Exception notification was executed."); Stringbuffer.append ("Method:"). Append (Joinpoint.getsignature (). GetName ()). Append ("An exception has occurred."); Stringbuffer.append ("Exception information is:"). Append (E.getmessage ());    System.out.println (Stringbuffer.tostring ()); }}
View Code

3. Defining facets, tangent points in context

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:mvc= "Http://www.springframework.org/schema/mvc"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xsi:schemalocation= "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/ spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/ Spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/ spring-mvc.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/ Spring-aop.xsd "><BeanID= "Serviceimpla"class= "Cuiyw.Spring.Service.ServiceImplA" /><BeanID= "Serviceaspectbean"class= "Cuiyw.Spring.Service.ServiceAspect" /><!--Configure a slice -<Aop:config>    <Aop:aspectID= "Serviceaspect"ref= "Serviceaspectbean">        <Aop:pointcutID= "Servicepointcut"expression= "Execution (* cuiyw.spring.service.*.* (..))" />        <!--Configuring a pre-notification -        <Aop:beforePointcut-ref= "Servicepointcut"Method= "Beforeadvice" />        <!--Configuring a pre-notification -        <Aop:afterPointcut-ref= "Servicepointcut"Method= "Afteradvice" />        <!--Configure post-return notifications -        <aop:after-returningPointcut-ref= "Servicepointcut"Method= "Afterreturnadvice"returning= "Result" />        <!--Configure surround Notifications -        <Aop:aroundPointcut-ref= "Servicepointcut"Method= "Aroundadvice" />        <!--Exception Notification -        <aop:after-throwingPointcut-ref= "Servicepointcut"Method= "Throwingadvice"throwing= "E" />    </Aop:aspect></Aop:config></Beans>
View Code

4. Invoking the service in main

        ApplicationContext context=New classpathxmlapplicationcontext (new string[]{" Applicationcontext.xml "});        Beanfactory Factory=context;        IService serviceImplA1= (iservice) factory.getbean ("Serviceimpla");        Serviceimpla1.service (
View Code

5. Error

        Serviceimpla Serviceimpla2=factory.getbean ("Serviceimpla", Serviceimpla.  Class);        Serviceimpla2.service (
View Code

Use the code above to test the following error, using the 4 interface in the way you can, this is the reference http://blog.csdn.net/two_people/article/details/51816964 in the

Bean named ' Serviceimpla ' is expected to being of type ' Cuiyw.Spring.Service.ServiceImplA ' but was actually of type ' com.sun. Proxy. $Proxy 4 '
View Code

Iv. Summary

It shows how AOP is implemented, but there are many ways to do it, and only one demo is written here. There are 3 hours to 2018, I wish you a happy New Year!

Spring's AOP II

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.