Spring Learning (13) AOP Technology understanding and use

Source: Internet
Author: User
Tags throwable log4j

First, what is AOP?
    aop技术是面向切面编程思想,作为OOP的延续思想添加到企业开发中,用于弥补OOP开发过程中的缺陷而提出的编程思想。AOP底层也是面向对象;只不过面向的不是普通的Object对象,而是特殊的AOP对象。AOP的关注点是组成系统的非核心通用服务模块(比如登录检查等),相对于普通对象,aop不需要通过继承、方法调用的方式来提供功能,只需要在xml文件中以引用的方式,将非核心服务功能引用给需要改功能的核心业务逻辑对象或方法中。最终实现对象的解耦。spring 中ioc技术实现了核心业务逻辑对象之间的解耦(如LoginAction与DaoImpl),aop技术实现的是核心业务逻辑对象与非核心通用服务之间的解耦(如LoginAction与LoginCheckInterceptor).
Ii. What are the benefits of AOP versus OOP?
    OOP,面对对象编程思想。OOP的问题不存在于开发阶段,在开发阶段和首次测试阶段中,使用OOP是效率最高也是最简单的一种方式。OOP问题体现在软件开发完毕之后的二次测试阶段,软件修改完毕之后,需要对软件中修改的方法进行重新测试,之后才可以上线运行。这时测试的对象是当前修改的方法 以及 和该方法具有级联/依赖关系的所有的其他方法。这样做显然了延长二次测试周期。    而使用aop在二次测试时,因为他是配置在xml文件中的,所以并不需要测试相关的所有类。
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.

publicclass StuAction {    publicaddStu(){        System.out.println("处理客户端提交的addStu.action请求");        //int i = 1/0;        return"success";    }    publicdelStu(){        System.out.println("处理客户端提交的selStu.action请求");        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 notification is mainly used for the core method call after the output of the log, so here to use the log4j, do not understand can pay attention to my blog, the next blog How to use log4j, here no longer repeat.

//define a notification class that implements Methodbeforeadvice-before notification Public  class logincheckadvice implements methodbeforeadvice {    //This method automatically executes before the core method executes    @Override     Public void before(Method arg0, object[] arg1, Object arg2)throwsThrowable {System.out.println ("Determine if there is currently a login user");//Determine whether follow-up core approach is performed based on the outcome of the decision}}//After notification Public  class loggeradvice implements afterreturningadvice{    Private StaticLogger Logger = Logger.getlogger (Loggeradvice.class);//This method will execute automatically after the core method has finished executing    @Override     Public void afterreturning(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 log message"); 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  class aroundadvice implements methodinterceptor {    @Override     PublicObjectInvoke(Methodinvocation invocation)throwsThrowable {//struts2 Interceptor Actioninvocation DispatcherSystem.out.println ("around notification-before the core method executes"); Object result = Invocation.proceed ();//Transfer the execution permission 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 the core method has been executed");returnResult }}//throws notice Public  class exceptionadvice implements throwsadvice {    //This method automatically executes after the core method performs an exception     Public void afterthrowing(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

<Beans xmlns="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 ">    <!--introduction of AOP namespaces, schame file requirements: Using the AOP technology provided by spring to add the functionality of the login check to an AOP group in spring, 1. Piece AOP Component [Struts2 Interceptor filter Filters Spring Notification] 2 notifies the class, core business logic Object [two objects with dependencies] in the IOC container- -    <bean id="Action" class="com.etoak.action.StuAction"/>     <bean id="LC" class="Com.etoak.util.LoginCheckAdvice"/ >    <bean id="Logger" class="Com.etoak.util.LoggerAdvice" />    <bean id="Around" class="Com.etoak.util.AroundAdvice"/>     <bean id="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 you need to refer to the functionality provided by this notification class Aop:pointcut Configuration Pointcut entry point: Used to describe where the notification execution is [executed] address: what/which methods are executed around the pointcut points to the A set of methods to add the login Check Feature expression property: A notification executes an expression that points to the execution result of the expression as a result of the execution of the pointcut expression, which is also a set of methods execution (* C            Om.etoak.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 [facets] --    <aop:config>        <aop:pointcut expression="Execution (* com.etoak.action.stu*.add* (..)) | | Execution (* com.etoak.action.*.del* (..)) " id="PC"/>        <aop:advisor advice-ref="LC" pointcut-ref="PC"/><!--reference the functionality provided by the id= "LC" to the set of methods that the id= "PC" points to.        <aop:advisor advice-ref="Logger" pointcut-ref="PC" />        <aop:advisor advice-ref="Around" pointcut-ref="PC"/>        <aop:advisor advice-ref="Exce" pointcut-ref="PC"/>     </aop:config></Beans>

Use the test class to check:

publicclass Test {    publicstaticvoidmain(String[] args) {        // TODO Auto-generated method stub        new ClassPathXmlApplicationContext("applicationContext.xml");        StuAction la = (StuAction)ac.getBean("action");        la.addStu();        la.delStu();    }}

The results are as follows:

Believe this show is pretty straightforward, right?
The use of AOP is so simple!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Spring Learning (13) 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.