Spring AOP annotation example

Source: Internet
Author: User

Spring AOP annotation example

In the previous article, I wrote two proxies of spring AOP. Here I started the implementation of AOP. I personally like the annotation method because it is more flexible, more powerful, and more scalable than the XML annotation method. So the XML-based AOP implementation is abandoned by me.

To implement Spring AOP, You need to import four packages. Here, we use maven to introduce the jar package and the jar package in the color annotation. The previous article has already introduced

<Dependency>
<GroupId> cglib </groupId>
<ArtifactId> cglib-nodep </artifactId>
<Version> 2.1_3 </version>
</Dependency>
<Dependency>
<GroupId> aopalliance </groupId>
<ArtifactId> aopalliance </artifactId>
<Version> 1.0 </version>
</Dependency>
<Dependency>
<GroupId> org. aspectj </groupId>
<ArtifactId> aspectjrt </artifactId>
<Version> 1.6.11 </version>
</Dependency>
<Dependency>
<GroupId> org. aspectj </groupId>
<ArtifactId> aspectjweaver </artifactId>
<Version> 1.6.11 </version>
</Dependency>

Add the following two sentences in the applicationContext-mvc.xml (or spring-mvc.xml) to declare an XML Schema instance

Xmlns: aop = "http://www.springframework.org/schema/aop"

Xsi: schemaLocation = "http://www.springframework.org/schema/aop

Http://www.springframework.org/schema/aop/spring-aop-3.2.xsd

Enable @ AspectJ Annotation

The configuration in the applicationContext-mvc.xml is as follows:

<! -- Start support for @ AspectJ annotation -->
<! -- If proxy-target-class is equal to true, cglib proxy is forcibly used, and proxy-target-class is false by default. If your class implements the interface, JDK proxy is used, if the cglib proxy is not used -->
<! -- Note: cglib proxy is recommended for standalone mode. Although JDK dynamic proxy is faster than cglib proxy, its performance is inferior to cglib -->
<Aop: aspectj-autoproxy proxy-target-class = "true"/>
<Context: annotation-config/>
<Bean id = "interceptor" class = "com. gcx. common. Interceptor"/>

It should be noted that the two cannot be less, specified at the beginning of the applicationContext-mvc.xml File

<Mvc: annotation-driven/>
<! -- Enable the component scanning function and automatically scan the components configured by annotation under the com. gcx package and its sub-package -->
<Context: component-scan base-package = "com. gcx"/>

Next, let's start to define the aspect. First, let's take a look at its basic knowledge.

* Joinpoint: a row in the Program Execution Process is (method), for example, a call to UserService. get () or an exception thrown by UserService. delete.
* Notification (Advice): the action taken by the "plane" for a "connection point", for example, com. spring. an Advice is used to record all the class methods in the service package. One slice can contain multiple "Advice", such as ServiceAspect.
* Pointcut: an assertion that matches the connection point. It is associated with a Pointcut expression in AOP. For example, the connection points of all notifications in TestAspect are determined by the entry point expression execution (* com. spring. service. impl.
* Target Object: The Object notified by one or more slices. For example, AServcieImpl and BServiceImpl, Spring AOP adopts proxy implementation during actual running, and actual AOP operates on the proxy object of TargetObject.
* AOP Proxy: There are two Proxy methods in Spring AOP: JDK dynamic Proxy and CGLIB Proxy. By default, when TargetObject implements an interface, JDK dynamic proxy is used, for example, AServiceImpl; otherwise, CGLIB proxy is used, for example, BServiceImpl. To use the CGLIB proxy, set the proxy-target-class attribute of <aop: config> to true.

Notification (Advice) Type

* Before advice: A notification executed Before a connection point. However, this notification cannot be executed Before a connection point.

* Post-notification (After advice): The Notification executed when a connection point exits (whether it is a normal return or an abnormal exit ).

* After return notification (After return advice): The Notification executed After a connection point is normal, excluding the exception thrown.

* Surround notification (Around advice): notifications that enclose a connection point, similar to the doFilter method of the Filter in the Servlet specification in the Web. You can customize the behavior before and after the method is called, or you can choose not to execute.

* After throwing an exception notification (After throwing advice): the notification that is executed when the method throws an exception and exits.

Define an interface and write the implementation class:

Public interface UserService {
Public void addUser (String userName, String password );
}

@ Service ("userService ")
Public class UserServiceImpl implements UserService {

@ Override
Public void addUser (String userName, String password ){
System. out. println ("-------------- User addUser -------------");
}

}

Define partition class

@ Aspect // define the Aspect
@ Component // declare that this is a Component
Public class Interceptor {

Private final static Log log = LogFactory. getLog (Interceptor. class );

/**
* This sentence is the method entry point.
* 1 execution (* com. wangku. spring. service. impl ..*.*(..))
* 2 execution: Indicates execution.
* 3 First * indicates the return value type. * It can be of any type.
* 4 com. spring. service. impl: indicates the scanned package.
* 5 ..: blocks sub-packages under it.
* 6 Second *: indicates which class to intercept, * indicates all classes
* 7 third *: represents the Method * represents any method
* 8 (...): Indicates whether all parameters of a method are supported.
*/
// Configure the entry point. This method does not have a method body and is mainly used to facilitate other methods of the same type.
@ Pointcut ("execution (* com. gcx. service. impl ..*.*(..))")
Private void aspect (){
System. out. println ("=============== enter the aspect method ================== ");
}

// Configure the surround notification to use the entry point registered on method aspect ()
@ Around ("aspect ()")
Public void around (JoinPoint joinPoint ){
Long start = System. currentTimeMillis ();
Try {
(ProceedingJoinPoint) joinPoint). proceed ();
Long end = System. currentTimeMillis ();
If (log. isInfoEnabled ()){
Log.info ("around" + joinPoint + "\ tUse time:" + (end-start) + "MS! "); // The execution speed is recorded here, which can be used as monitoring
}
} Catch (Throwable e ){
Long end = System. currentTimeMillis ();
If (log. isInfoEnabled ()){
Log.info ("around" + joinPoint + "\ tUse time:" + (end-start) + "MS with exception:" + e. getMessage ());
}
}
}
// Pre-notification and so on can have no JoinPoint Parameter
@ Before ("aspect ()")
Public void doBefore (JoinPoint joinPoint ){
System. out. println ("=========== execution of the pre-notification ====================== ");
If (log. isInfoEnabled ()){
Log.info ("before" + joinPoint );
}
}
// Configure post-notification to use the entry point registered on method aspect ()
@ After ("aspect ()")
Public void doAfter (JoinPoint joinPoint ){
System. out. println ("============= after the execution of the notification ==================== ");
If (log. isInfoEnabled ()){
Log.info ("after" + joinPoint );
}
}
// Configure the post-return notification to use the entry point registered on method aspect ()
@ AfterReturning ("aspect ()")
Public void afterReturn (JoinPoint joinPoint ){

System. out. println ("============= execution of the post-return notification ==================== ");
If (log. isInfoEnabled ()){
Log.info ("afterReturn" + joinPoint );
}
}
// Notification after the configuration throws an exception, using the entry point registered on method aspect ()
@ AfterThrowing (pointcut = "aspect ()", throwing = "ex ")
Public void afterThrow (JoinPoint joinPoint, Exception ex ){
If (log. isInfoEnabled ()){
Log.info ("afterThrow" + joinPoint + "\ t" + ex. getMessage ());
}
}
}
Test class

@ Test
Public void testAOP1 (){
// Start the Spring container
ApplicationContext ctx = new ClassPathXmlApplicationContext (new String [] {"classpath: applicationContext-mvc.xml", "classpath: applicationContext-dataSource.xml "});
UserService userService = (UserService) ctx. getBean ("userService ");
UserService. addUser ("zhangsan", "123456 ");
}

:

OK !! Simple spring AOP is implemented. On this basis, you can perform simple log management for AOP. My habit is to add the log logic code in the post notification. However, this method is not the most flexible. The next article will introduce the custom annotations of spring AOP to implement log management.

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.