Example to explain the AOP implementation in the Java Spring Framework _java

Source: Internet
Author: User
Tags aop sleep throwable java spring framework

Brief introduction
aspect-oriented programming (AOP) provides another way to think about the structure of a program, making up for the lack of object-oriented programming (OOP). In addition to classes (classes), AOP provides slices. Cut to the point of concern for modularity, such as transaction management across multiple types and objects. (These attention-point terms are often referred to as crosscutting (crosscutting) concerns.) )

One of the key components of spring is the AOP framework. Still, the spring IOC container does not depend on AOP, which means that you are free to choose whether to use AOP,AOP to provide a powerful middleware solution that makes the spring IOC container more complete.

Spring 2.0 AOP:

Spring 2.0 introduces a simpler and more powerful way to customize slices, and users can choose to use a schema-based approach or use @aspectj annotations. For new applications, if users use Java 5 Development, we recommend users to use the @aspectj style, otherwise you can use a pattern based style. Both of these styles fully support the notification (Advice) type and the AspectJ Pointcut language, although the spring AOP is actually still used for weaving (weaving).

This chapter focuses on the Spring 2.0 pair of model-based and @aspectj-based AOP support. Spring 2.0 retains the compatibility of spring 1.2 completely, and the next chapter discusses the underlying AOP support provided by the Spring 1.2 API.

AOP used in spring:

Provides declarative enterprise services, especially in lieu of EJB declarative services. The most important service is declarative transaction management (declarative transaction management), which is based on spring's abstract transaction management (transaction abstraction).

Allows users to implement custom slices, using AOP to refine the use of OOP.

Instance
we often use the following kinds of
1. Agent-based AOP
2, Pure simple Java object slice
3, @Aspect annotation form of
4, injection form of the ASPCET plane
Let's apply one to the next.
Let's write a few basic classes below.
Interface class:

/** 
 * Defines an interface 
 * 
/public interface sleepable { 
 
  /** 
   * Sleeping 
   method 
  /Void Sleep (); 
} 

Implementation class:

/** 
 * I realize sleeping interface 
/public class Chenllina implements sleepable { 
 
  @Override public void Sleep 
  () { 
    //TODO auto-generated method stub 
    System.out.println ("Good, it's time to go to bed!") "); 
  } 
} 

Enhanced classes:

/** 
 * Defines a sleep enhancement that simultaneously implements the front and rear/ 
 public 
class Sleephelper implements Methodbeforeadvice, Afterreturningadvice { 
 
  @Override public 
  void Afterreturning (Object ReturnValue, Method method, 
      object[] args, object target) Throws Throwable { 
     System.out.println ("Apply mask before going to bed"); 
  } 
 
  @Override public 
  Void Before (method method, object[] args, Object target) 
      throws Throwable { 
    System.out.println ("Dream after Bed"); 
  } 
 
 

I. Agent-based AOP

<!--Create an enhanced advice--> <bean id = "Sleephelper" class= "Com.tgb.springaop.aspect.SleepHelper"/> <bea N id= "Lina" class= "Com.tgb.springaop.service.impl.ChenLliNa"/> <!--define pointcuts match all sleep methods--> <bean id = "SLE Eppointcut "class=" Org.springframework.aop.support.JdkRegexpMethodPointcut "> <property name=" pattern "value= ". *sleep" ></property> </bean> <!--section enhancements + pointcuts combined--> <bean id= "Sleephelperadvisor" Clas 
     s= "Org.springframework.aop.support.DefaultPointcutAdvisor" > <property name= "Advice" ref= "Sleephelper"/> <property name= "Pointcut" ref= "Sleeppointcut"/> </bean> <!--define proxy object--> <bean id= "Lin 
      Aproxy "class=" Org.springframework.aop.framework.ProxyFactoryBean "> <property name=" target "ref=" Lina "/> <property name= "Interceptornames" value= "Sleephelperadvisor"/> <!--<property name= "ProxyInterfac Es "Value=" com.tgb.springAop.service.Sleepable "/>--> </bean> 

 

such as the configuration file:
The Pattern property specifies a regular expression that matches all the sleep methods
The purpose of using org.springframework.aop.support.DefaultPointcutAdvisor is to combine pointcuts and enhancements to form a complete slice
After the configuration is finished, a final proxy object is generated through Org.springframework.aop.framework.ProxyFactoryBean.
 
Second, plain simple Java object slices
Plain Simple Java object Section How do I say this, in my opinion, is relative to the first configuration, does not need to use the proxy, but through spring's internal mechanism to automatically scan , this time our configuration file should be modified as follows:
 

<!--Create an enhanced advice--> 
<bean id = "Sleephelper" class= "Com.tgb.springaop.aspect.SleepHelper"/> 
<!--target class--> 
<bean id= "Lina" class= "Com.tgb.springaop.service.impl.ChenLliNa"/> 
 
<!-- Configure pointcuts and notifications--> 
<bean id = "Sleepadvisor" class= "Org.springframework.aop.support.RegexpMethodPointcutAdvisor" > 
   <property name= "Advice" ref= "Sleephelper" ></property> 
   <property name= "pattern" value= " . *sleep "/> 
</bean> 
 
<!--automatic proxy configuration--> 
<bean class=" Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator "/> 

is not relative to the first kind of simple many, no longer to configure the agent.

iii. @Aspect form of annotations
as we know from our experience, the form of annotations is simpler than the configuration file, which needs to be annotated in the existing method or class:

/** 
 * Add enhancements through annotations 
/@Aspect @Component public 
class SleepHelper03 {   
   
  /* @Pointcut (" Execution (* Com.tgb.springaop.service.impl. *(..))") * * 
  @Pointcut ("Execution (* *.sleep (..))") 
  The public void Sleeppoint () {} 
   
  @Before ("Sleeppoint ()") is public 
  void Beforesleep () { 
    System.out.println (" Apply mask before going to bed ") 
  ; 
   
  @AfterReturning ("Sleeppoint ()") Public 
  void Aftersleep () { 
    System.out.println ("Dream After Bedtime"); 
  } 


The configuration file simply writes:

<!--scan package--> 
   <context:component-scan base-package= "Com.tgb" annotation-config= "true"/>  
   <! --AspectJ annotation--> 
   <aop:aspectj-autoproxy proxy-target-class= "true"/>  
    
   <!--target class--> 
   < Bean id= "Lina" class= "Com.tgb.springaop.service.impl.ChenLliNa"/>  


Iv. Injection form of the Aspcet slice
personally feel this is the simplest and most commonly used, but also the most flexible. The configuration file is as follows:

<!--target class--> 
  <bean id= "Lina" class= "Com.tgb.springaop.service.impl.ChenLliNa"/> <bean 
  id = " Sleephelper "class=" Com.tgb.springaop.aspect.SleepHelper02 "/> 
   
  <aop:config> 
    <aop:aspect ref=" Sleephelper "> 
       <aop:before method=" beforesleep "pointcut=" Execution (* *.sleep (..)) " /> 
       <aop:after method= "aftersleep" pointcut= "Execution (* *.sleep (..))" /> 
    </aop:aspect> 
  </aop:config> 


The SleepHelper02 classes mentioned in the configuration file are as follows:

/** 
 * Add enhancements through annotations * 
 /Public 
 
class SleepHelper02 {public 
  void Beforesleep () { 
    System.out.println ("Apply mask before going to bed"); 
  } 
  public void Aftersleep () { 
    System.out.println ("Dream After Bedtime"); 
  } 
 

Does

 
look simple enough that everyone will use Spring AOP?!
 
about how to call, there are several test classes written here, you can look at, basically the same:

 
/** * Config file spring_aop.xml via proxy/@Test public void Test () {ApplicationContext ct = new Classpathxmlapplicatio 
   
  Ncontext ("Spring_aop.xml"); 
   
  Sleepable sleeper = (sleepable) ct.getbean ("Linaproxy"); 
Sleeper.sleep (); /** * Config file spring_aop_01.xml Java object/@Test public void test01 () {ApplicationContext ct = new ClassPath 
   
  Xmlapplicationcontext ("Spring_aop_01.xml"); 
   
  Sleepable sleeper = (sleepable) Ct.getbean ("Lina"); 
Sleeper.sleep (); /** * Config file spring_aop_03.xml via aspect annotation/@Test public void test03 () {ApplicationContext ct = new ClassPath 
   
    Xmlapplicationcontext ("Spring_aop_03.xml"); 
   
  Sleepable sleeper = (sleepable) Ct.getbean ("Lina"); 
Sleeper.sleep (); /** * Profile Spring_aop_02.xml via apsect profile * @author Chenlina * @version May 31, 2015 a.m. 10:09:37/@Test public void 
   
  test02 () {ApplicationContext ct = new Classpathxmlapplicationcontext ("Spring_aop_02.xml"); Sleepable sleeper = (sleepable) ct.getbeAn ("Lina"); 
Sleeper.sleep (); 
 }


By testing the class you can see that no matter what the way to implement AOP their use is no different, the results of these test classes are the same:

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.