SPRING-AOP Learning

Source: Internet
Author: User
Tags define exception object object throwable

springaop Learning

Author:luojie

    1. 1. Basic Concepts in AOP

AOPthe generic term, notSpring Javaunique. I'm sorry .AOPthe terminology is not particularly intuitive. But if you letSpring Javato define your own terminology may be more confusing.

Aspect (Aspect): modularity of concerns that are distributed horizontally across multiple objects. In enterprise applications, transaction management is a typical crosscutting concern. The Springjava is implemented as an advisor or Interceptor (Interceptor). (By: Advisor is a combination of notification and pointcut, the interceptor actually refers to the notice, note in this document, the general will be surrounded by the notification is called interceptors, and other types of notifications called notifications, This is because the surround notification implements the AopAlliance.Intercept.IMethodInterceptor interface, and other notification types implement the notification interface under the SPRING.AOP namespace. )

Connection point (Joinpoint): A point in the execution of a program, such as a call to a method or a throw of a particular exception, can be called a connection point.

Notification (Advice): The behavior that the AOP framework takes at a connection point. There are several types of notifications, including "surround" notifications, "pre-Notifications" and "exception" notifications, and the types of notifications are discussed later in this article. Many AOP frameworks, including spring.net, model notifications as interceptors (interceptor) and maintain a "surround" interceptor chain around connection points.

Pointcut (Pointcut): Refers to the application conditions of a notification to determine which connection points a notification is to be applied to. The AOP framework should allow developers to specify pointcuts, for example, you can use regular expressions to specify a pointcut.

Introduce (Introduction): Adds the behavior of a method or field to a target object. Spring.net allows the introduction of new interfaces for any target object. For example, you can take advantage of the introduction of a tracking process that allows any object to implement the Iauditable interface at run time to simplify object state changes. (by: Also known as mixin, mixed)

Target object: Refers to the object that contains the connection point. Also known as being notified or being proxied to an object. (By: "The Notified object" is actually "the object to which the notification was applied", in the translation, the advised object or Proxied object is collectively referred to as the target object, which is more uniform)

AOP Proxy (Aopproxy): An object created by the AOP framework after the notification is applied to the target object. In Spring.net, an AOP agent is a dynamic agent that is created at run time by using IL code.

Weave in (Weaving): Assemble the facet to create a target object. Weaving can be done at compile time (for example, with the Gripper_loom.net compiler), or at run time. The spring.net performs the weaving at run time.



Various notification types include:

Surround notification (Around Advise): A notification of a connection point, such as a method call, that surrounds (by: that is, before and after the connection point is executed). This is one of the most powerful notifications. Surround notifications allow custom behavior to be performed before and after a method call. It can decide whether to allow the connection point to continue execution, or to "short-circuit" the connection point with its own return value or exception.

Pre-notification (before Advise): Executes before a connection point executes, but does not have the ability to prevent the connection point from continuing execution (unless it throws an exception).

Exception notification (Throws Advise): Executes when the method (connection point) throws an exception. Spring.net exception Notification is strongly typed (by: Spring.net uses the identity interface to define exception notifications, exception notification processing methods only follow certain naming rules, you can declare their parameters with a specific exception type, see 12.3.2.3), so you can catch a type of exception (and its subclasses) directly in your code. Exception) without the need to transition from exception.

Post notification (after returning Advise): Executes after the connection point has completed normal execution, for example, if the method returns normally without throwing an exception, the post-notification is executed.

Spring Java has built in all of these types of notifications. When applying, you should try to use a notification type that is minimal in functionality (as long as it is sufficient for the behavior you want to implement), which simplifies the programming model and reduces the likelihood of errors. For example, if you only need to update the cache with the return value of a method, then using a post-notification is more appropriate than wrapping the notification. Because, although the wrapping notification can accomplish the same function, the connection point always executes normally, without having to invoke the proceed () method of the Imethodinvocation interface in the post-notification to allow the connection point to continue executing, as in the case of surround notification. (By: In other words, because the surround notification can control the continuation of the connection point, the connection point is "shorted" if the proceed () method of the Imethodinvocation interface is not called), and the post-notification does not exist.

entry point isAOPthe key concepts that makeAOPfundamentally different from the old interception techniques. Pointcuts enable notifications to be independent ofOObeyond the inheritance hierarchy. For example, a wrapping notification for a declarative transaction can be applied to methods of different objects. Entry point isAOPof structural elements.

2. Jar Package

Spring Framework packages, and AOP-related jars.

3. Learning Examples

If you are making a slice of the controller, record the log that accesses the controller

Logaspect.java

@Component//scan, equivalent <bean>

@Aspect//equivalent to <aop:aspectref= "" >

Public class Logaspect {

Private Static Logger Log = Loggerfactory.getlogger (GetClass ());

@Around ("Within (Org.tedu.cloudnot.controller. *)")

Equivalent to <aop:around method= "Logcontroller" pointcut= "" >

Public Object Aroundcontroller (Proceedingjoinpointjoinpoint) throwsthrowable{

String targetName = Joinpoint.gettarget (). GetClass (). GetName ();

String methodName = Joinpoint.getsignature (). GetName ();

String description = "";

Class Targetclass = Targetclass.getmethods ();

Method[] methods = Targetclass.getmethods ();

for (Method method:methods) {

if (Method.getname (). Equals (MethodName)) {

class[] Clazzs = Method.getparametertypes ();

for (Class<?>clas:clazzs) {

String parametername = Clas.getname ();

Description = Description = "" + parametername;

}

}

}

log. info ("Enter Intocontroller---------------------------------");

log. info ("TargetName:" + TargetName + ";");

log. info ("MethodName:" + MethodName + ";");

log. info ("Parametertypes:" + description + ";");

object[] args = Joinpoint.getargs ();

log. info ("parametervalues" + Arrays. ToString(args));

Object object = null;

Try {

Object = Joinpoint.proceed ();

}catch(Exception ex) {

log. Error ("=============================controller method performs exception ==============");

Baseresult rr = new baseresult ();

Rr.seterrorcode ();

RR.SETERRORMSG);

return RR;

}

object[] Objs = Joinpoint.getargs ();

Log.info ("Returnresult:" + object);

return object;

}

Public void Afterthrowingcontroller (joinpoint joinpoint, Throwable e) {

String params = "";

if (Joinpoint.getargs ()! = null &&joinpoint.getargs (). length > 0) {

for (int i = 0; I<joinpoint.getargs (). length; i++) {

params + = Joinpoint.getargs () [i] + ";";

}

}

Try {

System. out. println ("------Exception notification start-------------");

System. out. println ("Exception code");

System. out. println ("exception information");

System. out. println ("Exception method" + (Joinpoint.gettarget (). Getclass.getname + "."

+joinpoint.getsignature (). GetName () + "()");

System. out. println ("Request parameters" + params);

}catch(Exception ex) {

log. Error ("= = Exception Notification exception =====");

log. Error ("Exception information: {}", Ex.getmessage ());

}

/*=========== log ============*/of the ground anomaly

log. Error ("Exception method: {} exception code: {} exception parameter: {} parameter {}", newobject[]{1,2,3,4});

}

4. Spring.xml Configuration

<aop:config>

<aop:pointcut expression= "(Within (com.me. *) or

Within (coom.me. *))"

Id= "Controllerpointcut"/>

<aop:aspect id = "Logaspect" ref= "Loggerbean" >

<aop:arount method= "Arountcontroller" pointcut-ref= "Contrllerpointcut"/>

<aop:after-throwing method= "Afterthrowingcontroller" pointcut-ref= "Controllerpointcut" throwing= "E"/>

</aop:aspect>

</aop:config>

* Need to add an AOP schema configuration

* You may need to add a custom scan annotation for AOP (not required here, tested, required with annotations)

* Possible if the AOP tangent program does not work, note that the configuration is likely to be written in Spring-servlet.xml (that is, the SPRINGMVC configuration file)

<context:component-scan base-package= "Com.spring.aop"/>

<aop:aspectj-autoproxy/>

<!--notify spring to use Cglib instead of JDK to generate proxy methods AOP can intercept controllers--

<aop:aspectj-autoproxy proxy-target-class= "true"/>

4. Expressions for SPRINGAOP

Execution of any public method:
Execution (Public * * (..))
Any execution of a method that begins with "set":
Execution (*set* (..))
Execution of any method of the Accountservice interface:
Execution (*com.xyz.service.accountservice.* (..))
The execution of any method defined in the service package:
Execution (*com.xyz.service.*.* (..))
The execution of any method defined in a service package or a child package:
Execution (*com.xyz.service. *.*(..))
Any connection point in the service package (only method execution in spring AOP):
Within (com.xyz.service.*)
Any connection point in the service package or child package (only method execution in spring AOP):
Within (Com.xyz.service. *)
Any connection point that implements the proxy object for the Accountservice interface (only method execution in SPRINGAOP):
This (Com.xyz.service.AccountService)
The ' This ' is used more in the binding form:-Please refer to the section in the following discussion notice about how to make the proxy object accessible within the notification body.
Any connection point that implements the target object of the Accountservice interface (only method execution in SPRINGAOP):
Target (Com.xyz.service.AccountService)
' Target ' is used more in the binding form:-Please refer to the section on how to make the target object accessible within the notification body in the following section of the discussion notice.
Any one that takes only one parameter and the parameters passed in at run time implements the connection point for the Serializable interface (only method execution in spring AOP)
Args (java.io.Serializable)
' args ' is used more in the binding form:-Please refer to the section in the following discussion notice about how to make a method parameter accessible within the notification body. Note that the pointcut given in the example is different from execution (* * (java.io.Serializable)): Args only matches when the incoming parameter is serializable (Serializable) at dynamic runtime, and execution The type of the signature declaration that passed in the parameter implements the serializable interface when it is matched.
Any connection point in the target object that has a @Transactional annotation (only method execution in SPRINGAOP)
@target (org.springframework.transaction.annotation.Transactional)
' @target ' can also be used in the binding form: Please refer to the section on how to make the annotation object accessible within the notification body in the following section of the discussion notice.
The type of any target object declaration has a connection point for @transactional annotations (only method execution in SPRINGAOP)
@within (org.springframework.transaction.annotation.Transactional)
' @within ' can also be used in the binding form:-Please refer to the section in the following discussion notice about how to make the annotation object accessible within the notification body.
Any one executed method has a @Transactionalannotation connection point (only method execution in SPRINGAOP)
@annotation (org.springframework.transaction.annotation.Transactional)
' @annotation ' can also be used in the binding form:-Please refer to the section in the following discussion notice about how to make the annotation object accessible within the notification body.
Any one accepts a parameter, and the passed in parameter at run time implements the connection point of @classified annotation (only method execution in SPRINGAOP)
@args (com.xyz.security.Classified)

SPRING-AOP Learning

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.