Spring uses ASPECTJ annotations and XML configuration to implement Aop_java

Source: Internet
Author: User
Tags aop log4j

This article demonstrates the use of ASPECTJ annotations and XML configuration in spring to implement AOP in two ways

Here is Java Project that implements AOP using the AspectJ annotation
The first is the Applicationcontext.xml file located under Classpath

 <?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" Www.springframework.org/schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:aop=" Http://ww 
      W.springframework.org/schema/aop "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 htt P://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http:// Www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <!-- Enable ASPECTJ support for annotation--> <aop:aspectj-autoproxy/> <bean id= "Usermanager" class= "Com.jadye" R.annotation.usermanagerimpl "/> <bean id= securityhandler" class= "Com.jadyer.annotation.SecurityHandler"/& 
Gt </beans> 

Then the service layer interface and the implementation class

Package com.jadyer.annotation; 
  Public interface Usermanager {public void AddUser (string username, string password); 
  public void Deluser (int userId); 
  Public String Finduserbyid (int userId); 
public void ModifyUser (int userId, string Username, string password); 
 
/** * Above Usermanager is the interface of the service layer * The Usermanagerimpl below is the implementation class of the service layer interface * * * Package com.jadyer.annotation; public class Usermanagerimpl implements Usermanager {public void AddUser (string username, string password) {Syst 
  EM.OUT.PRINTLN ("------usermanagerimpl.adduser () is invoked------"); 
  The public void Deluser (int userId) {System.out.println ("------usermanagerimpl.deluser () is invoked------"); Public String Finduserbyid (int userId) {System.out.println ('------Usermanagerimpl.finduserbyid () is invoked-- 
    ----"); 
  Return "iron unfamiliar"; public void ModifyUser (int userId, string Username, string password) {System.out.println ("------Usermanagerim Pl.modifyuser () is invoked------");  } 
}

Next is the cut class using the AspectJ annotation annotation

Package com.jadyer.annotation; 
 
Import Org.aspectj.lang.annotation.After; 
Import Org.aspectj.lang.annotation.Aspect; 
Import Org.aspectj.lang.annotation.Pointcut; 
 
@Aspect public 
class Securityhandler { 
  /** 
   * definition pointcut 
   * @see pointcut name is Addaddmethod (), This method has no return value and parameter 
   * @see The method is an identity without calling/ 
  @Pointcut ("Execution (* add* (..))")//matching all methods 
  beginning with add private void Addaddmethod () {}; 
   
  /** 
   * Definition Advice 
   * @see indicates to which pointcut subscribed joinpoint 
  //@Before ("Addaddmethod ()") for our advice application. 
  @After ("Addaddmethod ()") 
  private void CheckSecurity () { 
    System.out.println ("------" checksecurity is invoked "------"); 
  }     

Finally, the client test class

Package com.jadyer.annotation; 
Import Org.springframework.context.ApplicationContext; 
 
Import Org.springframework.context.support.ClassPathXmlApplicationContext; /** * Spring's support for AOP: using the annotation approach * @see------------------------------------------------------------------------- ------------* @see Spring offers an AOP feature that is powerful and configurable, with the default implementation of JDK dynamic proxies * @see using Spring's AOP does not need to inherit relevant things, nor does it need to implement interfaces * @see But there's a front Conditions: Because it is the JDK dynamic proxy, so if you want to generate a proxy, the class must implement an interface to the line * @see if the class does not have a implements interface and still uses the default AOP implementation of spring, then an error occurs * @see Classes that typically need to generate proxies are classes of the service layer, so they usually draw an interface. The habit of developing interface-oriented programming * @see-------------------------------------------------------------------------------------* @see The basic steps to complete the AOP example in annotation are the following * @see 1, Spring2.0 dependency pack configuration.   Additional annotation Support * @see * Spring_home//dist//spring.jar * @see * Spring_home//lib//log4j//log4j-1.2.14.jar * @see * Spring_home//lib//jakarta-commons//commons-logging.jar * @see * Spring_home//lib//aspectj//*.jar * @see 2, cross-cutting concerns Point modularization, establish Securityhandler.java * @seE 3, using annotations to designate Securityhandler as aspect * @see 4, use annotations to define advice and Pointcut * @see 5, enable ASPECTJ support for annotation, and configure target classes and aspect classes to IOC 
Container * @see 6, Development client * @see-------------------------------------------------------------------------------------* * public class Client {public static void main (string[] args) {ApplicationContext factory = new Classpathxmlapplic 
    Ationcontext ("Applicationcontext.xml"); 
    Usermanager Usermanager = (usermanager) factory.getbean ("Usermanager"); 
  Usermanager.adduser ("Zhang Ling", "02200059");  } 
}

The following is Java Project
that implements AOP using XML configuration Files First is the Applicationcontext-cglib.xml file in the src root

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "HT Tp://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/AOP http:// Www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http:// Www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <!--forced to use cglib agent--> <!--<aop:aspectj- Autoproxy proxy-target-class= "true"/>--> <bean id= "Usermanager" class= "Com.jadyer.cglib.UserManagerImpl"/ > <bean id= "Securityhandler" class= "Com.jadyer.cglib.SecurityHandler"/> <aop:config> ; Aop:aspect id= "Securityaspect" ref= "SecuriTyhandler "> <aop:pointcut id=" addaddmethod "expression=" Execution (* add* (..)) " /> <aop:before method= "checksecurity" pointcut-ref= "Addaddmethod"/> </aop:aspect> </aop:c 
 
Onfig> </beans> <!--all methods that match the start of add execution (* add* (..)) 
 
All methods of matching all classes under the Com.jadyer.servcices.impl package execution (* com.jadyer.servcices.impl.*.* (..)) All methods that match the Add or del start of the Com.jadyer.servcices.impl package execution (* com.jadyer.servcices.impl.*.add* (..)) | | 
 Execution (* com.jadyer.servcices.impl.*.del* (..))  -->

Then the service layer interface and the implementation class

Package com.jadyer.cglib; 
  Public interface Usermanager {public void AddUser (string username, string password); 
  public void Deluser (int userId); 
  Public String Finduserbyid (int userId); 
public void ModifyUser (int userId, string Username, string password); 
 
/** * Above Usermanager is the service layer interface * The USERMANAGERIMPL below is the implementation class of the service layer interface * * * Package com.jadyer.cglib; 
    public class Usermanagerimpl {//implements usermanager {public void AddUser (string username, string password) { 
  SYSTEM.OUT.PRINTLN ("------usermanagerimpl.adduser () is invoked------"); 
  The public void Deluser (int userId) {System.out.println ("------usermanagerimpl.deluser () is invoked------"); Public String Finduserbyid (int userId) {System.out.println ('------Usermanagerimpl.finduserbyid () is invoked-- 
    ----"); 
  Return "John"; public void ModifyUser (int userId, string Username, string password) {System.out.println ("------Usermanagerim Pl.modifyuser () is invoked------");  } 
}

Next is the cut class specified in the Applicationcontext-cglib.xml

Package com.jadyer.cglib; 
 
Import Org.aspectj.lang.JoinPoint; 
 
/** 
 * The customer invocation information is passed to the advice 
 * @see You can add a joinpoint parameter to the advice to get the method name and parameter value of the client invocation 
 * @see There are fewer cases of using AOP to write something like this in the future, and we mainly use the transaction provided by spring 
 @see about this, and know. The following is the example code */Public 
class Securityhandler { 
  private void checksecurity (Joinpoint joinpoint) {for 
    (int i = 0; I<joinpoint.getargs (). length; i++) { 
      System.out.println (Joinpoint.getargs () [i]);//Get the parameter value of the method called by the client 
    System.out.println ( Joinpoint.getsignature (). GetName ()); Gets the method name called by the client 
    System.out.println ("------" checksecurity is invoked "------"); 
  } 
 

Finally, the client test class

Package com.jadyer.cglib; 
Import Org.springframework.context.ApplicationContext; 
 
Import Org.springframework.context.support.ClassPathXmlApplicationContext; /** * @see--------------------------------------------------------------------------------------------------* The difference between the JDK dynamic agent and the Cglib agent * @see 1..JDK dynamic Proxy proxy for classes that implement interfaces @see 2..CGLIB proxies can be used on class proxies, generating a subclass of the specified class. Because it is inherited, it is best not to use the final declaration * @see for the target class--------------------------------------------------------------------------------- -----------------* @see The choice of proxy mode * @see 1. If the target object implements the interface, the JDK dynamic proxy is implemented by default, and the Cglib generation agent is enforced to implement AOP * @see 2. If the target object is not implemented interface, you must introduce Cglib, where spring will automatically switch between JDK dynamic proxy and cglib agent * @see 3. The comparison encourages business objects to be programmed for interfaces, so that JDK dynamic proxies are encouraged. Because we are agents of the target, is generally the business object * @see-------------------------------------------------------------------------------------- ------------* @see To use the Cglig agent * @see 1. New Cglib Library: Spring_home//lib//cglib//*.jar * @see 2. Add a new configuration label to force the use of Cglib proxy <a Op:aspectj-autoproxy proxy-target-class= "true"/> * @see --------------------------------------------------------------------------------------------------* * Public Class Client {public static void main (string[] args) {ApplicationContext factory = new Classpathxmlapplicationco 
     
    ntext ("applicationcontext-cglib.xml"); When Usermanagerimpl implements the Usermanager interface, Spring automatically uses the JDK dynamic Proxy//If the project has been introduced into the Cglib library and enforces the Cglib proxy in the configuration file. 
     
    At this point spring will use the Cglib proxy//usermanager Usermanager = (usermanager) factory.getbean ("Usermanager"); Because the Usermanagerimpl does not implement the Usermanager interface at this time, the receive type can no longer use the Usermanager interface//And the Cglib Library has been introduced into the project, although the Cglib agent is not enforced in the configuration file. 
     
    But spring automatically uses the Cglib proxy usermanagerimpl Usermanager = (Usermanagerimpl) factory.getbean ("Usermanager"); 
  Usermanager.adduser ("Wu San Province", "02200059"); 
 } 
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.