Examples of AOP programming patterns under the Java Spring Framework _java

Source: Internet
Author: User
Tags aop java spring framework

The key component of the spring framework is the aspect-oriented programming (AOP) framework. Aspect-oriented programming not only breaks down the logic of the program into different parts called the so-called worry. The functionality of an application that spans multiple points is known as crosscutting concerns and these crosscutting concerns are distinguished from the business logic concepts of the application. There are a variety of common good examples like logging, auditing, declarative transactions, security, and caching.

The key units in modular OOP are classes, while the modular units in AOP are slices. Dependency Injection can help you decouple application objects from each other and AOP can help you isolate crosscutting concerns from the objects they affect. AOP is the same programming language as Perl,.net,java and other triggers.

The Spring AOP module provides an application that interceptors block, for example, when you execute a method, you can add additional functionality to a method that is executed before or after.

AOP Terminology:
Before we start using AOP, familiarize yourself with the concepts and terminology of AOP. These terms are not specific to spring, and the problem is all about AOP.
Recommended types
Spring can be used in 5 of the following recommendations:

Customization aspect implementation

Spring based on XML-mode AOP
you need to import the spring AOP schema as described below:

<?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: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 ">

  <!--bean definition & AOP specific Configuration-->

</beans>

You also need the ASPECTJ library in the following application classpath. These libraries are available in the ASPECTJ installation ' Lib ' directory and can be downloaded from the Internet.

    • Aspectjrt.jar
    • Aspectjweaver.jar
    • Aspectj.jar

Declare a slice
One aspect is to use the <aop:aspect> element declaration, and the support bean is to use the ref attribute for the following reference:

<aop:config>
  <aop:aspect id= "Myaspect" ref= "Abean" >
  ...
  </aop:aspect>
</aop:config>

<bean id= "Abean" class= "..." > ...
</bean>

The "Abean" here will configure and rely on injection, just like any other spring bean we've seen in the previous chapters.

Declaring a Pointcut
A pointcut can help you determine the interest (that is, the method) of the connection point that you want to perform differently. At the same time, with the configuration of the XML Schema Foundation, the pointcut will be defined as follows:

<aop:config>
  <aop:aspect id= "Myaspect" ref= "Abean" >

  <aop:pointcut id= "Businessservice"
   expression= "Execution (* com.xyz.myapp.service.*.* (..))" /> ...
  </aop:aspect>
</aop:config>

<bean id= "Abean" class= "..." > ...
</bean>

The following example defines a "businessservice" pointcut that matches the available package Com.yiibai the execution of the GetName () method under the Student class:

<aop:config>
  <aop:aspect id= "Myaspect" ref= "Abean" >

  <aop:pointcut id= "Businessservice"
   expression= "Execution (* com.yiibai.Student.getName (..))" /> ...
  </aop:aspect>
</aop:config>

<bean id= "Abean" class= "..." > ...
</bean>

Statement of recommendation
You can declare any five suggested use of the <aop:{advice name}> element below to give a <aop:aspect>:

<aop:config> <aop:aspect id= "Myaspect" ref= "Abean" > <aop:pointcut id= "businessservice" Expressio n= "Execution (* com.xyz.myapp.service.*.* (..))" /> <!--A before advice definition--> <aop:before pointcut-ref= "Businessservice" method= "Dorequi" Redtask "/> <!--A after advice definition--> <aop:after pointcut-ref=" Businessservice "method="  Dorequiredtask "/> <!--a after-returning advice definition--> <!--The Dorequiredtask method must have Parameter named RetVal--> <aop:after-returning pointcut-ref= "Businessservice" returning= "RetVal" od= "Dorequiredtask"/> <!--a after-throwing advice definition--> <!--the Dorequiredtask method must h Ave parameter named ex--> <aop:after-throwing pointcut-ref= "Businessservice" throwing= "ex" method= "DoR" Equiredtask "/> <!--a around advice definition--> <aop:around pointcut-ref=" busInessservice "method=" dorequiredtask/> ... </aop:aspect> </aop:config> <bean id= "Abean" Clas

 S= "..." > ... </bean>

You can use the same dorequiredtask or different methods for different suggestions. These methods will be defined as part of the crossbar module.

An AOP example based on XML Schema
To understand the concepts mentioned above that relate to the XML schema, let's write an example that will implement several recommendations.

This is the content of the Logging.java file. This is actually an example of a crossbar module, which defines the various points of the method being invoked.

Package Com.yiibai;

public class Logging {/** * the ' is ' the ' method 
  which I would ' to ' execute * before
  a selected method Execu tion.
  */Public
  void Beforeadvice () {
   System.out.println ("Going to the Setup Student Profile");
  }

  /** * This are the method 
  which I would like to execute
  * After a selected method execution.
  */Public
  void Afteradvice () {
   System.out.println ("Student profile has been setup.");
  }

  /** 
  * is the "method" which I would like to execute * If any method
  returns.
  */Public
  void Afterreturningadvice (Object retVal) {
   System.out.println ("Returning:" + retval.tostring ());
  }

  /** * is the "method"
  which I would like to execute
  * If there are an exception raised.
  */Public
  void Afterthrowingadvice (IllegalArgumentException ex) {
   System.out.println ("There has been Exception: "+ ex.tostring ());  
  }
  
}

The following are the contents of the Student.java file:

Package Com.yiibai;

public class Student {
  private Integer age;
  private String name;

  public void Setage (Integer age) {
   this.age = age;
  }
  Public Integer Getage () {
  System.out.println (' Age: ' + age);
   return age;
  }

  public void SetName (String name) {
   this.name = name;
  }
  Public String GetName () {
   System.out.println ("Name:" + name);
   return name;
  
  public void Printthrowexception () {
  System.out.println ("Exception raised");
    throw new IllegalArgumentException ();
  }


The following are the contents of the Mainapp.java file:

Package Com.yiibai;

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mainapp {public
  static void Main (string[] args) {
   ApplicationContext context = 
       new Classpathxml ApplicationContext ("Beans.xml");

   Student Student = (Student) context.getbean ("Student");

   Student.getname ();
   Student.getage ();
   
   Student.printthrowexception ();
  }


The following is the configuration file Beans.xml file:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" 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 "> <aop:config> <aop:aspect id=" Log "ref=" Logging "> <aop:pointcut id=" Sele Ctall "expression=" Execution (* com.yiibai.*.* (..)) " /> <aop:before pointcut-ref= "SelectAll" method= "Beforeadvice"/> <aop:after pointcut-ref= "SelectAll"
               method= "Afteradvice"/> <aop:after-returning pointcut-ref= "SelectAll" returning= "RetVal" method= "Afterreturningadvice"/> <aop:after-throwing pointcut-ref= "SelectAll"
       Ex        method= "Afterthrowingadvice"/> </aop:aspect> </aop:config> <!--Definition for student b EAN--> <bean id= "student" class= "com.yiibai.Student" > <property name= "name" value= "Zara"/> &LT;PR Operty name= "Age" value= "one"/> </bean> <!--Definition for logging aspect--> <bean id= "Loggin

 G "class=" com.yiibai.Logging "/> </beans>

After creating the source code and the bean configuration file, let's run the application. If all goes well, this will print the following information:

Going to the Setup student profile.
Name:zara
Student profile has been setup.
Returning:zara
going to the Setup student profile.
Age:11
Student profile has been setup.
Returning:11
going to the Setup student profile.
Exception raised
Student profile has been setup.
There has been an exception:java.lang.IllegalArgumentException
..... Other exception content

Explain, above define <aop:pointcut> Select all Packages Com.yiibai the method defined below. Let's assume that if you want to have a specific approach to execution before or after the comment, you can define the pointcut with the actual class and method name instead of the asterisk (*) of the pointcut definition to narrow the execution. The following is a modified XML configuration file to display the concepts:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" 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 "> <aop:config> <aop:aspect id=" Log "ref=" Logging "> <aop:pointcut id=" SelectA ll "expression=" Execution (* com.yiibai.Student.getName (..)) " /> <aop:before pointcut-ref= "SelectAll" method= "Beforeadvice"/> <aop:after pointcut-ref= "selectAll" meth  od= "Afteradvice"/> </aop:aspect> </aop:config> <!--Definition for student Bean--> <bean Id= "Student" class= "com.yiibai.Student" > <property name= "name" value= "Zara"/> <property "age" Val Ue= "One "/> </bean> <!--Definition for logging aspect--> <bean id=" Logging "class=" Com.yiibai.Logg

 ing "/> </beans>

If you perform the sample application for these configuration changes, this will print the following information:

Going to the Setup student profile.
Name:zara
Student profile has been setup.
Age:11
Exception raised ...
Other exception content

AOP based on @aspectj
@ aspectj is a common Java class that uses Java 5 annotations for declarative style annotations. Support for @ ASPECTJ is enabled by the following elements in the configuration file that includes your xml-based schema.

<aop:aspectj-autoproxy/>

You will also need the ASPECTJ library in the classpath of the following applications. These libraries can be installed in the AspectJ ' lib ' directory and can download them from the Internet.

    • Aspectjrt.jar
    • Aspectjweaver.jar
    • Aspectj.jar

Declare a slice
The aspect class is like any other normal bean and may have methods and fields, just like any other class, but they will be labeled @aspect as follows:

Package org.xyz;

Import Org.aspectj.lang.annotation.Aspect;

@Aspect public
class Aspectmodule {

}

They will be configured in XML like any other bean, as follows:

<bean id= "Myaspect" class= "Org.xyz.AspectModule" >
  <!--Configure properties of aspect here as normal-->
</bean>

Declaring a Pointcut
An entry point helps to determine the rights (i.e. methods) of the connection points to be executed with different opinions. At the same time using @aspectj's basic configuration work, the Pointcut declaration has two parts:

Pointcut expression, deciding which methods to execute we are interested in

A pointcut signature contains the name and any number of arguments. The actual body of the method is irrelevant and should actually be empty.

The following example defines a class named ' Businessservice ' that will match the com.xyz.myapp.service in execution under the available package for each method:

Import Org.aspectj.lang.annotation.Pointcut;

@Pointcut ("Execution (* com.xyz.myapp.service.*.* (..))")//Expression 
private void Businessservice () {}// Signature

The following example defines a GetName () method that is named ' GetName ' pointcut that matches the available package Com.yiibai under the Student class:

Import Org.aspectj.lang.annotation.Pointcut;

@Pointcut ("Execution (* com.yiibai.Student.getName (..))") 
private void GetName () {}

Statement of recommendation
You can declare any of the five suggestions given below using the @{advice-name} annotation. This assumes that a businessservice () of the method of a pointcut signature has been defined:

@Before ("Businessservice ()") Public
void Dobeforetask () {
 ...
}

@After ("Businessservice ()") Public
void Doaftertask () {
 ...
}

@AfterReturning (pointcut = "businessservice ()", returning= "RetVal") public
void Doafterreturnningtask (Object RetVal) {
 //can intercept retVal here.
 ...
}

@AfterThrowing (pointcut = "businessservice ()", throwing= "ex") public
void Doafterthrowingtask (Exception ex) {
 //You can intercept thrown exception.
 ...
}

@Around ("Businessservice ()") Public
void Doaroundtask () {
 ...
}

You can define any comments that are built into pointcuts. The following is an example of a proposal to define an inline pointcut:

@Before ("Execution (* com.xyz.myapp.service.*.* (..))")
Public Dobeforetask () {
...
}
@AspectJ based on AOP examples
To understand the underlying concepts that relate to @aspectj AOP, let's write an example that will implement several recommendations.

This is the content of the Logging.java file. This is actually an example of an aspect module that defines the various points of the method being invoked.

Package Com.yiibai;
Import Org.aspectj.lang.annotation.Aspect;
Import Org.aspectj.lang.annotation.Pointcut;
Import Org.aspectj.lang.annotation.Before;
Import Org.aspectj.lang.annotation.After;
Import org.aspectj.lang.annotation.AfterThrowing;
Import org.aspectj.lang.annotation.AfterReturning;

Import Org.aspectj.lang.annotation.Around; @Aspect public class Logging {/** Following are the definition for a pointcut to select * All the methods available.
  So advice would be called * to all the methods.
  * * @Pointcut ("Execution (* com.yiibai.*.* (..))") private void SelectAll () {}/** * This is the ' method ' which I would like to execute * before a selected method Execu
  tion.
  */@Before ("SelectAll ()") public void Beforeadvice () {System.out.println ("Going to setup student profile.");
  }/** * is the "method" which I would like to execute * After a selected method execution. */@After ("SelectAll ()") public void Afteradvice () {System.out.println ("StuDent profile has been setup. ");}
  /** * is the "method" which I would like to execute * if any method returns. */@AfterReturning (pointcut = "SelectAll ()", returning= "RetVal") public void Afterreturningadvice (Object retVal) {S
  Ystem.out.println ("Returning:" + retval.tostring ());
  }/** * is the "method" which I would like to execute * if there is a exception raised by no method. */@AfterThrowing (pointcut = "SelectAll ()", throwing = "ex") public void Afterthrowingadvice (illegalargumentexception  
  Ex) {System.out.println ("There has been an exception:" + ex.tostring ());

 }
  
}

The following are the contents of the Student.java file:

Package Com.yiibai;

public class Student {
  private Integer age;
  private String name;

  public void Setage (Integer age) {
   this.age = age;
  }
  Public Integer Getage () {
  System.out.println (' Age: ' + age);
   return age;
  }

  public void SetName (String name) {
   this.name = name;
  }
  Public String GetName () {
   System.out.println ("Name:" + name);
   return name;
  public void Printthrowexception () {
   System.out.println ("Exception raised");
   throw new IllegalArgumentException ();
  }


The following are the contents of the Mainapp.java file:

Package Com.yiibai;

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mainapp {public
  static void Main (string[] args) {
   ApplicationContext context = 
       new Classpathxml ApplicationContext ("Beans.xml");

   Student Student = (Student) context.getbean ("Student");

   Student.getname ();
   Student.getage ();
   
   Student.printthrowexception ();
  }


The following is the configuration file Beans.xml file:

<?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: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 ">

  <aop:aspectj-autoproxy/>

  <! --Definition for student Bean--> <bean id= "student" class= "com.yiibai.Student"
  >
   <property Name = "Name" value= "Zara"/>
   <property name= "age" value= "one"/>   
  </bean>

  <!--Definition For logging aspect-->
  <bean id= "Logging" class= "com.yiibai.Logging"/> 
   
</beans>

After creating the source program and the bean configuration file, let's run the application. If all goes well, this will print the following information:

Going to the Setup student profile.
Name:zara
Student profile has been setup.
Returning:zara
going to the Setup student profile.
Age:11
Student profile has been setup.
Returning:11
going to the Setup student profile.
Exception raised
Student profile has been setup.
There has been an exception:java.lang.IllegalArgumentException
..... Other exception content

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.