SPRING3.0 Learning-AOP object-oriented programming _spring AOP XML configuration Patterns __spring3.0

Source: Internet
Author: User
Tags aop ticket jboss
1. The theory of passage

In software, some behaviors are generic. such as logging, security, and transaction management, they have a common feature that is distributed across multiple applications, a feature known as crosscutting concerns (cross-cutting concerns).

DI (Dependency injection) helps to apply decoupling between objects, and AOP enables the decoupling of crosscutting concerns from the objects they affect.

Common examples of applying slices: logs, declarative transactions, security, and caching.

The following include support for the spring slice, including how to declare a generic class as a slice and how to use annotations to create slices.

After reading this article, you can look back to the following passage.

Aspect-oriented programming has four kinds of calls in spring AOP: Method calls before, after, and exception to add other methods, method calls before and after other methods, the method of parameters passed to other methods, a new interface implementation as a parent class interface to other methods belong to the method, here to focus on understanding " The other method "is written separately from the method you would have called, which is low coupling." When you call a method, sping AOP does something else for this method in other classes.

The first three of these four types are easy to understand and use, it is simply that this method runs with additional methods running, and the fourth note is that Spring AOP allows you to force this interface into a new interface type without changing the original interface and implementation. The new method is then invoked through Spring di (dependency injection), looking at 8 in detail and introducing new features through the page.




2, what is facing the plane programming.

Inheritance and delegation are the most common object-oriented technologies that implement common functionality. Facets provide an alternative to inheritance and delegation, and are clearer and simpler in many scenarios.

When using aspect-oriented programming, we still define common functionality in one place, but we can provide a declarative way to define where this functionality is applied, without having to modify the affected classes.

crosscutting concerns can be modularized into special classes, which are called slices . 3. Terms for cutting plane: notifications, connection points and pointcuts, slices I use my own words to say, the slice is a class, the function of this class is to complete the specified action at the specified position of the subordinate action, the specified position has a selection first, can be created object, method call, variable change, etc. These choices are the connection points, and you can decide to select a subset of them, the selected part is the tangent, of course, the selection process is reflected in the code, after the selection, once these points are run, such as a call to a class, the plane in the class of a method will be called to complete other functions, This method of being invoked is the notification. So, you can simplify to the following relationship: Slice: Class. Tangent: The action of the specified code that is concerned with the slice. (although it can be a creation object, a method call, a variable change, but spring 3.0 is only supported for the method invocation, which is the tangent of a method's Classpath +) connection point: A code action that can be used as a pointcut. Notification: Method, an extra method at the tangent point. 3.1, notice (Advice)-5 kinds

section of work is called notice.

The notification defines what the slice is and when it is used. In addition to describing the work to be done on the cut, the notification also solves the question of when to perform this work.

It should be applied before a method is called. After. Before and after. Or only when the method throws an exception.

5 Types of notifications

· Before-invokes the notification before the method is invoked.

· After-invokes a notification after the method is invoked, regardless of whether the method was executed successfully.

· after-returning-invokes a notification after the method has successfully executed.

· after-throwing-invokes a notification after the method throws an exception.

· The Around-method executes a custom behavior before and after the call, and the notification method "wraps" up.

3.2, connection point (joinpoint)

A connection point is a point in which the slice can be inserted during application execution, which is precisely the timing of the program's operation, such as when a method is invoked, when an exception is thrown, or even when a field is modified.

The slice code can use these points (timing) to insert into the normal flow of the application and add new behavior.

3.3. tangent (poincut)

A slice (what is the slice). Only need to notify limited connection points instead of all connection points. The pointcut defines which of the connection points the notification needs to have effect.

The pointcut matches one or more connection points to which the notification is to be woven.

We usually specify these pointcuts using explicit class and method names.

In popular terms, pointcuts are a collection of valid connection points relative to different notifications .

3.4, cutting surface (Aspect)

A slice is a collection of notifications and pointcuts that informs you what to do. When. The pointcut determines where to make the notification. For example, we have to buy tickets at the station's ticket window or at the point of sale (tangent), which is 8 o'clock in the morning to 5 o'clock in the afternoon (notice-when), and the action is to pay for the ticket (notice-what to do).

3.5. Introduction (Introduction)

Introduction is a description of a process that means that we add a new method or property to an existing class. We can introduce a class as a notification into the class being notified so that the class is changed without changing the class being notified.

3.6, weaving (weaving)

section at the specified connection point (that is, the notification is notified at the Pointcut notification method, the notification is introduced into a class that is notified and is woven into the target object, which is always said to have added a method to the notification class, which is to weave, in the final analysis, to create a proxy class for the notified class and add a method to the proxy class. On the face of it, the proxy class adds a method, that is, weaving.

Weaving is the process of applying a slice to a target object to create a new proxy object. The slice is woven into the target object at the specified connection point.

Can be woven at multiple points of the target object.

By wrapping slices in the proxy class, spring weaves slices into the spring-managed bean at run time.

compilation period --the slice is woven when the target class is compiled.

• This approach requires a special compiler.

· AspectJ is woven into the plane in this way.

class Load period --the slice is woven when the target class is loaded into the JVM.

• This approach requires a special ClassLoader (ClassLoader), which enhances the byte code of the target class before the target class is introduced to the application.

· The LTW (load-time weaving) of AspectJ 5 supports the weaving of facets in this way.

Runtime --the slice is woven during a period of time during the application run.

• In general, the AOP container dynamically creates a proxy object for the target object when you are weaving the slice.

· Spring AOP is the run-time, dynamic creation of a proxy object for the target object to achieve the weaving. When the method call is blocked. The proxy executes the slice logic before calling the target bean. Spring does not create a proxy object until a bean that needs to be represented is applied.

4. Spring's support for AOP

Creating a pointcut to define the connection points that the cut is woven into is the basic function of the AOP framework. 4.1, the current AOP framework is the tripod situation

· AspectJ (HTTP://ECLIPSE.ORG/ASPECTJ);

· JBoss AOP (HTTP://WWW.JBOSS.ORG/JBOSSAOP);

· Spring AOP (http://www.springframework.org). 4.2. Spring offers 4 kinds of unique AOP support

The first 3 are all spring agent-based AOP variants, so spring's support for AOP is limited to method blocking . If the AOP requirements exceed the category of simple method interception (such as constructor or attribute blocking), consider implementing the slice in AspectJ, and injecting the spring bean into the ASPECTJ slice using spring's Di (Dependency injection):

• Classic AOP based on agent;

• @AspectJ the annotation-driven slice;

• Pure Pojo plane;

• Injection-type ASPECTJ section (for spring versions).

Classic Spring AOP uses Proxyfactorybean, and because there are simpler ways to do this, this is no longer an introduction.

4.3. Spring only supports method connection points

AspectJ and JBoss also provide field and constructor access points in addition to method pointcuts. So, with spring alone, we can't build fine-grained notifications or use constructor connection points. In this case, we can use aspect to assist Spring AOP.

4.4. The tangent points specify the connection point

We use Pointcuts to select the connection points, and then different notifications to match the different pointcuts. In spring AOP, you need to define pointcuts by using ASPECTJ pointcut expressions.

4.5. ASPECTJ pointcut Indicators supported by Spring AOP:

ARG () limits the connection point matching parameter to the specified type of execution method

@args () limits the method by which the connection point matching parameter is executed by the specified annotation callout

Execution () is used to match the execution method of the connection point

This () restricts the connection point to match the AOP Proxy's bean reference to a class of the specified type

Target () limits the connection point to match the target object to a class of the specified type

@target () Restricts the connection points to match specific execution objects, which correspond to classes that have annotations of the specified type

Within () limits the connection point to match the specified type

@within () Restricts the connection point to the type that the specified annotation is annotated (when using spring AOP, the method is defined in the class that is annotated by the specified annotation)

@annotation limit match with specified callout connection point

Only the execution Pointcut indicator is the only execution match, while the other pointcut indicators are used to limit matching.

4.6, Write pointcuts, the last statements will be added to the XML configuration file

Note: The path that is written is the path of the interface class, and the Pointcut is in the interface class rather than in the concrete implementation class.

Does not focus on the return type, does not focus on the parameter type, and introduces the Pointcut when the method executes

Execution (* Com.springination.springidol.Instrument.play (..))

Increase the limit-and define the package path for the Pointcut (the latter is superfluous). )

Execution (* Com.springination.springidol.Instrument.play (..))

and within (com.springinaction.springidol.*)

After spring2.5, you can qualify the Bean by ID

Execution (* Com.springination.springidol.Instrument.play (..))

and within (com.springinaction.springidol.*)

and Bean (Eddie)

Of course, you can also use reverse operation

Execution (* Com.springination.springidol.Instrument.play (..))

and within (com.springinaction.springidol.*)

and Bean (Eddie)

and!bean (EDDIE2)

4.7. Declaring slices in XML

AOP configuration element Description

<aop:advisor> Defining AOP Notifications

<aop:after> define AOP Post notifications (regardless of whether the method being notified succeeds)

<aop:after-returning> Define AOP after-returning notifications

<aop:after-throwing> Define after-throwing Notification

<aop:around> Define AOP Surround notifications

<aop:aspect> definition Slice

<aop:aspect-autoproxy> Enable @aspectj annotation-driven slices

<aop:before> Define AOP forward notifications

<aop:config> the AOP configuration element at the top level. Most <AOP:*> elements must be contained within the <aop:config> element

<aop:declare-parents> introduces additional interfaces for notified objects and transparently implements

<aop:pointcut> Define Pointcuts

5. Example of a tangent point

First you need to build a spring environment, and if you don't have your own spring environment, you can refer to the article

http://blog.csdn.net/bestcxx/article/details/52488620

http://blog.csdn.net/bestcxx/article/details/52620482

Spring AOP requires four additional jar packs, Aopalliance-1.0.jar,aspectjweaver-1.8.9.jar,aspectjrt-1.8.9.jar,aspectjtools-1.8.9.jar

Download Address: http://download.csdn.net/detail/bestcxx/9654632

(If you use maven then downloading the jar pack would be a very simple thing to do,

Build up your MAVEN environment, http://blog.csdn.net/bestcxx/article/details/52126907.

Search for the dependency statement of the jar package you need to add to the Pom.xml file and automatically download to the local MAVEN library

Http://mvnrepository.com/artifact/org.apache.servicemix.bundles/org.apache.servicemix.bundles.aspectj/1.8.9_1)

5.1, interface class Aopperformer.java


Content

Package STU.BESTCXX.SPRINGTEST.SPRINGAOP;

/**
 * Spring AOP Test Interface
 * @author wujiejecket
 * * */public
interface Aopperformer {public
	void Perform ();
}

5.2, interface implementation class, as a Bean,aopperformerimpl.java

Content

Package Stu.bestcxx.springtest.springaopimpl;
Import Stu.bestcxx.springtest.springaop.AopPerformer;
/**
 * Spring AOP Test Bean
 * @author wujiejecket */public
class Aopperformerimpl implements Aopperformer {
	@Override public
	Void Perform () {
		//TODO auto-generated method stub
		System.out.println ("performer sings");
	}

5.3, AOP called method class, that is, the method is woven into the tangent of the class, Audience.java

Content

Package Stu.bestcxx.springtest.springaopimpl;
/**
 * Spring AOP Test 
 * The notification that is woven into the 
 audience's action as a woven content * * 
 @author wujiejecket
 *
* * * public class Audience {
	/**
	 * before performing * * Public
	void Takeseats () {
		System.out.println (" Springaop method: The audience sat in their seats. ");
	}
	
	/**
	 * Before the performance/public
	void Turnoffcellphones () {
		System.out.println () Springaop method: The audience adjusted the phone to a shutdown state. ");
	}
	
	/**
	 * After the show * * Public
	void applaud () {
		System.out.println ("Springaop method: All the audience got up and applauded");
	}
	
	/**
	 * Performance failure/public
	void Demandrefund () {
		System.out.println ("Springaop method: All audiences pour applause");
	}

5.4. Spring XML configuration file, Applicationcontextaop.xml

Content

<?xml version= "1.0" encoding= "UTF-8"?><!--Generalized Spring XML configuration--> <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:util=" Http://www.springframework.org/schema/util "xmlns:aop=" Http://www.springframework.org/schema/aop "xsi:schemalocation=" Http://www.springframework.org/schema/beans http ://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http:// Www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http:// Www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://
	Www.springframework.org/schema/util/spring-util-3.0.xsd "> <context:annotation-config/> <!--performer--> <bean id= "Aopperformerimpl" class= "Stu.bestcxx.springtest.springaopimpl.AopPerformerImpl"/&Gt <!--viewers--> <bean id= "Audience" class= "Stu.bestcxx.springtest.springaopimpl.Audience" ></bean> < !--set pointcuts for interface classes--> <aop:config> <aop:aspect ref= "Audience" > <!----> <aop:before POINTCU t= "Execution (* stu.bestcxx.springtest.springaop.AopPerformer.perform (..))" method= "Takeseats" before/> <!-- > <aop:before pointcut= "Execution (* stu.bestcxx.springtest.springaop.AopPerformer.perform (..))" method= " Turnoffcellphones after "/> <!----> <aop:after-returning pointcut=" Execution (* STU.BESTCXX.SPRINGTEST.S Pringaop. Aopperformer.perform (..)) " Method= "Applaud"/> <!--after--> <aop:after-throwing pointcut= "Execution (* STU.BESTCXX.SPRINGTEST.SPRI Ngaop. Aopperformer.perform (..)) " method= "Demandrefund"/> </aop:aspect> </aop:config> </beans>

5.5, test class, Aopperformerimpltest.java

Content

Package Stu.bestcxx.springtest.springaopimpl;

Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.test.annotation.DirtiesContext;
Import org.springframework.test.context.ContextConfiguration;
Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
Import org.springframework.test.context.transaction.TransactionConfiguration;

Import Stu.bestcxx.springtest.springaop.AopPerformer;

@DirtiesContext
@RunWith (springjunit4classrunner.class)
@ContextConfiguration (locations={"classpath: Spring/applicationcontextaop.xml "}"
@TransactionConfiguration (transactionmanager=) Defaulttransactionmanager ", defaultrollback=false) public
class Aopperformerimpltest {
	@Autowired
	Private Aopperformer Aopperformer;
	
	@Test public
	void Testperform () {
		aopperformer.perform ();
	}
}

Run Result:


5.6. Unified configuration of pointcuts at the same location in spring XML

To visually compare, we add an audience

Audience2.java

Package Stu.bestcxx.springtest.springaopimpl;
/**
 * Spring AOP Test 
 * The notification that is woven into the 
 audience's action as a woven content * * 
 @author wujiejecket
 *
* * * public class Audience2 {
	/**
	 * before performing * * Public
	void Takeseats () {
		System.out.println (" SpringAOP2 method: The audience sat in their seats. ");
	}
	
	/**
	 * Before the performance/public
	void Turnoffcellphones () {
		System.out.println () SpringAOP2 method: The audience adjusted the phone to a shutdown state. ");
	}
	
	/**
	 * After the show * * Public
	void applaud () {
		System.out.println ("SpringAOP2 method: All the audience got up and applauded");
	}
	
	/**
	 * Performance failure/public
	void Demandrefund () {
		System.out.println ("SpringAOP2 method: All audiences pour applause");
	}

Applicationcontextaop.xml content expansion to:

<?xml version= "1.0" encoding= "UTF-8"?><!--Generalized Spring XML configuration--> <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:util=" Http://www.springframework.org/schema/util "xmlns:aop=" Http://www.springframework.org/schema/aop "xsi:schemalocation=" Http://www.springframework.org/schema/beans http ://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http:// Www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http:// Www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://
	Www.springframework.org/schema/util/spring-util-3.0.xsd "> <context:annotation-config/> <!--performer--> <bean id= "Aopperformerimpl" class= "Stu.bestcxx.springtest.springaopimpl.AopPerformerImpl"/&Gt <!--viewers--> <bean id= "Audience" class= "Stu.bestcxx.springtest.springaopimpl.Audience" ></bean> < !--viewers 2--> <bean id= "Audience2" class= "Stu.bestcxx.springtest.springaopimpl.Audience2" ></bean> <!
			--Set Pointcuts for interface classes--> <aop:config> <!--decentralized configuration pointcuts--> <aop:aspect ref= "Audience" > <!----> <aop:before pointcut= "Execution (* stu.bestcxx.springtest.springaop.AopPerformer.perform (..))" method= " Takeseats "/> <!--before--> <aop:before pointcut=" Execution (* Stu.bestcxx.springtest.springaop.AopPerformer . Perform (..)) " method= "Turnoffcellphones"/> <!--after--> <aop:after-returning pointcut= "Execution (* STU.BESTCXX.SPRI Ngtest.springaop.AopPerformer.perform (..)) " Method= "Applaud"/> <!--after--> <aop:after-throwing pointcut= "Execution (* STU.BESTCXX.SPRINGTEST.SPRI Ngaop. Aopperformer.perform (..)) " method= "Demandrefund"/> </aop:aspect> <!--centralized configuration cutPoint--> <aop:aspect ref= "Audience2" > <!--declaring pointcuts,--> <aop:pointcut expression= "Execution (* STU.BESTC Xx.springtest.springaop.AopPerformer.perform (..)) " Id= "perform"/> <!--before--> <aop:before pointcut-ref= "perform" method= "Takeseats"/> <!-- --> <aop:before pointcut-ref= "perform" method= "Turnoffcellphones"/> <!----> Returning pointcut-ref= "perform" method= "applaud"/> <!--after--> <aop:after-throwing pointcut-ref= "PE Rform "method=" Demandrefund "/> </aop:aspect> </aop:config> </beans>

Test method is unchanged, Aopperformerimpltest.java

Run result is

6, the declaration of surrounding notifications-such as statistics run time

Sometimes we need to share information between a predecessor and a post notification. Declaration wrapping provides this service that performs the execution of the method of the class that is being woven into the pointcut into a tangent class, runs the required functional code before and after, and, in the final analysis, the functional code of the predecessor notification and the post notification is written in the same method.

Public * Methods (* by proxy method) {

/* Code 1*/

By proxy method

/* Code 2*/

6.1 Below is the code example

6.1.1 Write Pointcut class Audiencewatch.java

Content

Package Stu.bestcxx.springtest.springaopimpl;
Import Org.aspectj.lang.ProceedingJoinPoint;
The public class Audiencewatch {
	/**
	 * Proceedingjoinpoint lets us invoke the notified method in the notification method
	 * @param joinpoint
	* * public void Watchperforance (Proceedingjoinpoint joinpoint) {
		try {
			System.out.println) ("The audience sits in their seats.") ");
			System.out.println ("The viewers are adjusting their phones to mute status.") ");
			Long Start=system.currenttimemillis ();
			
			Executes the method being notified, without which the notification will not be made for
			(int i=0;i<=1000;i++) {
				joinpoint.proceed ();				
			}
			
			Long End=system.currenttimemillis ();
			System.out.println ("The audience greeted with enthusiastic applause");
			System.out.println ("The performer spends the time" + (End-start) + "milliseconds");
			
		catch (Throwable e) {
			//TODO auto-generated catch block
			e.printstacktrace ();
		}
	}
}

6.1.2 Spring XML configuration file Applicationcontextaoparound.xml

Content

<?xml version= "1.0" encoding= "UTF-8"?><!--Generalized Spring XML configuration--> <beans xmlns= "http:/ /www.springframework.org/schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:context=" http ://w 

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.