Spring AOP (aspect-oriented programming) _ Getting Started Demo

Source: Internet
Author: User
Tags stub throwable

Software 152 Liu Anmin

AOP is the continuation of OOP and is the abbreviation for Aspect oriented programming, meaning aspect-oriented programming. AOP is actually a continuation of the GOF design pattern, and the design pattern pursues the decoupling between the caller and the callee, and AOP can be said to be an implementation of this goal.

The implementation of AOP technology, mainly divided into two major categories: first, the use of dynamic Agent technology, the use of interception of messages to decorate the message to replace the original object behavior, the second is the use of static implantation, the introduction of a specific syntax to create "facet", so that the compiler can be woven into the relevant "aspects" The code. However, the technical characteristics of AOP are the same, namely:

1 Join point: is an exact point of execution in a program execution, such as a method in a class. It is an abstract concept, and when implementing AOP, there is no need to define a join point.

2 point Cut (pointcut): essentially a structure that captures the connection point. In AOP, you can define a point cut to capture calls to related methods.

3 Advice (Notification): Is the execution code for point cut, which is the specific logic for performing "facets".

4 aspect (aspect): Point cut and advice are combined as aspect, which resembles a class defined in OOP, but it represents more of a horizontal relationship between objects.

5 introduce (introduced): introduces an additional method or property for an object, thus achieving the purpose of modifying the object structure. Some AOP tools refer to them as mixin.

The technical features described above form the basic AOP technology, and most AOP tools implement these technologies. They can also be the basic terminology for studying AOP technology.

For example, suppose there is a single application in which a shared data must be accessed concurrently, and first, the data is encapsulated in a data object, and there will be multiple access classes dedicated to accessing the same data object at the same time.

*demo Experiment:

A. Create two interface classes: Testserviceinter,testserviceinter2, the code is as follows:

Testserviceinter

Public interface Testserviceinter {

public void SayHello ();

}

TestServiceInter2

Public interface TestServiceInter2 {

public void Saybye ();

}

B. Create a class Test1service implement the above interface

public class Test1service implements Testserviceinter,testserviceinter2 {

private String name;

public void SetName (String name) {

THIS.name = name;

}

@Override

public void SayHello () {

SYSTEM.OUT.PRINTLN ("HI" +name);

}

@Override

public void Saybye () {

System.out.println ("Bye" +name);

}

}

C. Create the Applicationcontext.xml, configure the necessary data sources and the Proxied objects, with the following code:

<?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:context= "Http://www.springframework.org/schema/context"

xmlns:tx= "Http://www.springframework.org/schema/tx"

xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.5.xsd

Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd ">

<!--Configure the object to be proxied--

<bean id= "Test1service" class= "Com.ansibee.aop.Test1Service" >

<property name= "name" value= "Guan Yu" ></property>

</bean>

</beans>

D. Create a pre-notification class Mymethodbeforeadvice implement the Methodbeforeadvice interface in order to execute this code before executing the SayHello () method. The code is as follows:

public class Mymethodbeforeadvice implements methodbeforeadvice{

/**

* Method: Called methods name

* Args: Parameters passed to method

* Target: Destination object

*/

@Override

public void before (method, object[] args, Object target) throws Throwable {

TODO auto-generated Method Stub

System.out.println ("*************");

System.out.println ("Log Record:" +method.getname ());

}

}

Create a post-notification class Myafterreturningadvice implement the Afterreturningadvice interface in order to execute this code after the Saybye () method is executed. The code is as follows:

public class Myafterreturningadvice implements Afterreturningadvice {

@Override

public void Afterreturning (Object returnvalue, method, object[] args, object target) throws Throwable {

TODO auto-generated Method Stub

SYSTEM.OUT.PRINTLN ("Close resources");

}

}

Finally create a surround notification class Mymethodinterceptor implement Methodinterceptor interface, surround notification = pre-notification + target method execution + post notification, proceed () method is used to start the target method execution. The code is as follows:

public class Mymethodinterceptor implements Methodinterceptor {

@Override

Public Object Invoke (Methodinvocation arg0) throws Throwable {

TODO auto-generated Method Stub

System.out.println ("Execute before calling method");

Object obj = Arg0.proceed ();

System.out.println ("Execute after calling method");

return obj;

}

}

E. After completing the above operation, go to the Applicationcontext.xml file and configure it accordingly. The code is as follows:

</bean>

<!--Configuring a pre-notification-

<bean id= "Mymethodbeforeadvice" class= "Com.ansibee.aop.MyMethodBeforeAdvice" ></bean>

<!--define the access point for the pre-notification

<bean id= "Mymethodbeforeadvicefilter" class= "Org.springframework.aop.support.NameMatchMethodPointcutAdvisor" >

<property name= "Advice" ref= "Mymethodbeforeadvice" ></property>

<property name= "Mappednames" >

<list>

<value>sayHello</value>

</list>

</property>

</bean>

<!--configuring post notifications-

<bean id= "Myafterreturningadvice" class= "Com.ansibee.aop.MyAfterReturningAdvice" ></bean> <!-- Configure surround Notifications-

<bean id= "Mymethodinterceptor" class= "Com.ansibee.aop.MyMethodInterceptor" ></bean>

<!--configuring proxy objects--

<bean id= "Proxyfactorybean" class= "Org.springframework.aop.framework.ProxyFactoryBean" >

<!--Configure the agent's interface set--

<property name= "Proxyinterfaces" >

<list>

<value>com.ansibee.aop.TestServiceInter</value>

<value>com.ansibee.aop.TestServiceInter2</value>

</list>

</property>

<!--to weave notifications into proxy objects--

<property name= "Interceptornames" >

<!--is equivalent to associating a pre-notification with a proxy object, and you can think of notifications as interceptors--

List>

<!--weaving pre-notification, post notification, surround notification-

<value>MyMethodBeforeAdviceFilter</value>

<!--using a custom pointcut to control front-to-

<value>MyAfterReturningAdvice</value>

<value>MyMethodInterceptor</value>

</list>

</property>

<!--notifies the Proxied object that you can specify--

<property name= "target" ref= "Test1service" ></property>

</bean>

F. After completing a series of configurations, you can test the code of the test class as follows:

public class Testmain {

public static void Main (string[] args) {

ApplicationContext ac = new Classpathxmlapplicationcontext ("Com/ansibee/aop/applicationcontext.xml");

Testserviceinter ts = (testserviceinter) ac.getbean ("Proxyfactorybean");

Ts.sayhello ();

((TestServiceInter2) ts). Saybye ();

}

}

Then run Java application, running the result

Spring AOP (aspect-oriented programming) _ Getting Started Demo

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.