Spring Framework Learning (9) AOP Technology understanding and use

Source: Internet
Author: User
Tags aop object object throwable log4j

Content derived from: AOP Technology understanding and use

First, what is AOP?

AOP technology is the aspect-oriented programming idea, which is added to the enterprise development as the continuation idea of OOP (object-oriented programming), which is used to make up the defects in the development process of OOP.

The underlying AOP is also object oriented, but it is not a normal object object, but a special AOP object. The focus of AOP is the non-core Generic service modules that make up the system (such as login checks, etc.), and AOP does not need to provide functionality through inheritance, method invocation, or in the form of a reference in an XML file, relative to ordinary objects. Reference non-core service functionality to the core business logic object or method that needs to be changed. Finally, the decoupling of the object is realized. The IOC technology in spring enables decoupling between core business logic objects (such as Loginaction and Daoimpl), and AOP technology enables decoupling between core business logic objects and non-core generic services (such as Loginaction and Logincheckinterceptor).

Ii. What are the benefits of AOP versus OOP?

The problem with OOP is not in the development phase, and using OOP is the most efficient and simplest way to use it during the development phase and the first Test phase. The OOP problem is embodied in the two test phases after software development, and after the software has been modified, the modified method in the software needs to be re-tested before it can be run on line. The object being tested is the currently modified method and all other methods that have a cascade/dependency on the method. This obviously extends the test cycle by two times. While using AOP in two Tests, because he was configured in an XML file, there is no need to test all related classes.

How do I use AOP in spring?

We use an example to illustrate how to use AOP in spring,
Here we provide a class stuaction that adds login check functionality for the core business logic methods (Addstu, Delstu) in this class.

 Public class stuaction {    public  String addstu () {        System.out.println (" Processing client-submitted addstu.action requests ");         // int i = 1/0;        return "Success";    }      Public String Delstu () {        System.out.println ("processing the selstu.action request submitted by the client");         return "Success";    }}

The AOP technology in spring provides four basic types of notifications:

    • Before notification ~ Notification before the core method executes Methodbeforeadvice
    • After notification ~ Notification after the core method is executed Afterreturningadvice
    • Around notification ~ Notification of core method execution Before+after filter, Interceptor is a around notification methodinterceptor
    • Throws notification ~ Notification that the core method executes after an exception is performed Throwsadvice

These four kinds of notifications we all come to test under:
Note: When testing the ATHROWS notification, uncomment the stuaction int i = 1/0; and we create an exception to test.
In addition, after notifications are primarily used to output logs after the core method call ends, log4j is used here.

//define a notification class that implements Methodbeforeadvice-before notification Public classLogincheckadviceImplementsMethodbeforeadvice {//This method automatically executes before the core method executes@Override Public voidbefore (Method arg0, object[] arg1, Object arg2)throwsthrowable {System.out.println ("Determine if there is currently a login user"); //decide whether to follow the core method based on the result of Judgment    }}//After notification Public classLoggeradviceImplementsafterreturningadvice{Private StaticLogger Logger =Logger.getlogger (loggeradvice.class); //This method automatically executes after the core method has finished executing@Override Public voidafterreturning (Object arg0, Method arg1, object[] arg2, object Arg3)throwsThrowable {//TODO auto-generated Method StubSystem.out.println ("Logging after core method execution is complete"); //record a log messageLogger.error ("This is an error level of log information"); Logger.warn ("This is a warn level of log information"); Logger.info ("This is an info-level log Message"); Logger.debug ("This is a debug-level log Message"); }}//around Notice Public classAroundadviceImplementsMethodinterceptor {@Override PublicObject invoke (Methodinvocation invocation)throwsThrowable {//struts2 Interceptor Actioninvocation DispatcherSYSTEM.OUT.PRINTLN ("Around notification-before the core method executes"); Object result=invocation.proceed (); //Transfer execution permissions of the request to the core business logic method Addstu/selstu//result-execution results of the Core method Addstu ()/selstu ()System.out.println ("result--" +result);//SuccessSYSTEM.OUT.PRINTLN ("Around notification-after core method execution")); returnresult; }}//throws Notice Public classExceptionadviceImplementsThrowsadvice {//This method automatically executes after the core method executes an exception     Public voidafterthrowing (method, object[] args, Object target, Exception ex) {System.out.println ("Core method execution is abnormal ... Exception Information "+ex.getmessage ()); }}

Log4j.properties

log4j.rootlogger=Info, etoak1,etoak2log4j.appender.etoak1=  Org.apache.log4j.ConsoleAppenderlog4j.appender.etoak1.layout=  Org.apache.log4j.TTCCLayoutlog4j.appender.etoak2=org.apache.log4j.FileAppenderlog4j.appender.etoak2. file=c://log4j.htmllog4j.appender.etoak2.layout=org.apache.log4j.htmllayout

Well, get ready to work, so how do we configure AOP in the Spring container?
The point is coming!
To configure AOP in Applicationcontext.xml:
First import all packages in spring in AOP, log4j package

<Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:mvc= "Http://www.springframework.org/schema/mvc"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.2.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/con Text/spring-context-3.2.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/ Mvc/spring-mvc-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/s Pring-aop-3.2.xsd ">    <!--introducing the AOP namespace, schame file requirements: Using the AOP technology provided by spring to add the functionality of the login check to an AOP component in spring, 1. AOP Component [Struts2 Blocker filter filter Spring notification] 2 Configure the notification class, core business logic Object [two objects with dependencies] in the IOC container -    <BeanID= "Action"class= "Com.etoak.action.StuAction"/>    <BeanID= "LC"class= "Com.etoak.util.LoginCheckAdvice"/>    <BeanID= "Logger"class= "Com.etoak.util.LoggerAdvice"/>    <BeanID= "Around"class= "Com.etoak.util.AroundAdvice"/>    <BeanID= "Exce"class= "Com.etoak.util.ExceptionAdvice"></Bean>    <!--3 using AOP to refer a notification class to a business logic object aop:config: Configuring an AOP component [how to use the notification class] 3.1 describes who needs to reference the functionality provided by this notification class to who AOP: Pointcut Configure Pointcut entry points: used to describe where the notification execution is [executed] address: what/which methods are executed around the pointcut pointing to the need to add a login check A set of methods for a Function expression property (expression): A notification executes an expression that points to the execution result of an expression as a result of the execution of the pointcut expression, and also a set of methods execution (* Com.etoa            K.action.*.* (..))         Execution (1 2) Execution () the contents of the expression 1 are used to qualify the method's return value * 2 for the location of the method, the name Com.etoak.action.*.* (..) 3.2 Assembly notification class + Pointcut forms an AOP component [tangent] -    <Aop:config>        <Aop:pointcutexpression= "Execution (* com.etoak.action.stu*.add* (..)) | | Execution (* com.etoak.action.*.del* (..))"ID= "PC"/>        <Aop:advisorAdvice-ref= "LC"Pointcut-ref= "PC"/><!--reference the functionality provided by this notification class id= "LC" to the set of methods that the id= "PC" points to. -        <Aop:advisorAdvice-ref= "Logger"Pointcut-ref= "PC"/>        <Aop:advisorAdvice-ref= "Around"Pointcut-ref= "PC"/>        <Aop:advisorAdvice-ref= "Exce"Pointcut-ref= "PC"/>    </Aop:config></Beans>

Use the test class to check:

 Public class Test {    publicstaticvoid  main (string[] args) {        // TODO auto-generated Method stub        New Classpathxmlapplicationcontext ("Applicationcontext.xml");         = (stuaction) ac.getbean ("Action");        La.addstu ();        La.delstu ();    }}

The results are as follows:

Spring Framework Learning (9) AOP Technology understanding and use

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.