First, the concept of AOP
The abbreviation for AOP (Aspect oriented programming), for aspect programming, is the main function of enhancing the processing of code.
Understand the meaning of aspect-oriented programming: Add new functionality to your code without changing the original program.
There are two concepts that you need to understand to implement aspect-oriented programming:
> pointcut: You can insert enhanced processing methods, such as the Fun () method of the original object.
> Enhanced Processing Type: Inserts a new feature before or after the original object fun () method.
Second, Spring AOP simple Application
1. Create a new Java project
2. Download the jar packages required by the Spring AOP and ASPECTJ framework to the website and add the required jar files to the project.
3. Add the user entity class to the project
Package Com.jbit.fsd.entity;public class User {private int id;private String username;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;}}
4. Add the data Access layer interface and implementation classes, and add the appropriate methods
Package Com.jbit.fsd.dao;import java.util.list;import com.jbit.fsd.entity.user;//data Access Layer Interface public interface Userdao { Public list<user> getAll ();p ublic void addUser (user user);
Implementation class:
Package Com.jbit.fsd.dao.impl;import Java.util.arraylist;import Java.util.list;import Com.jbit.fsd.dao.UserDao; Import Com.jbit.fsd.entity.user;public class Userdaoimpl implements Userdao {@Overridepublic list<user> getAll () {//Operation database reads all data list<user> list=new arraylist<user> (); List.add (new User ()); List.add (new User ()); List.add (New User ()); return list;} @Overridepublic void AddUser (user user) {System.out.println ("add Success");}}
5. Add a business processing layer interface and implementation class
Package Com.jbit.fsd.service;import Java.util.list;import Com.jbit.fsd.dao.userdao;import com.jbit.fsd.entity.User ;p Ublic interface UserService {public list<user> getAll ();p ublic void addUser (user user);
Implementation class:
Package Com.jbit.fsd.service.impl;import Java.util.list;import Com.jbit.fsd.dao.userdao;import Com.jbit.fsd.entity.user;import Com.jbit.fsd.service.userservice;public class Userserviceimpl implements Userservice{private Userdao dao;//is injected through spring in public void Setdao (Userdao dao) {This.dao = DAO;} @Overridepublic list<user> GetAll () {System.out.println ("Doing Business with adding users! "); return Dao.getall ();} @Overridepublic void AddUser (user user) {
SYSTEM.OUT.PRINTLN ("Doing Business with adding users!") ");d ao.adduser (user);}}
6. Adding an AOP Enhanced processing class
Package Com.jbit.fsd.aop;import Org.apache.commons.logging.log;import org.apache.commons.logging.LogFactory; public class Serviceloging {private log log = Logfactory.getlog (This.getclass ());p ublic void Beforeservice () {Log.info (" The AOP method is called! ");}}
7. Create a new Applicationcontext.xml file in the SRC directory
<?xml version= "1.0" encoding= "UTF-8"?><!---Application context definition for Jpetstore's business layer. -Contains bean references to the transaction manager and to the DAOs in-dataaccesscontext-local/jta.xml (see web. xml) "Contextconfiglocation"). --><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"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.xsdHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-2.5.xsdHttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "><!-- Decoupling and--><bean id= "Userdao" class= "Com.jbit.fsd.dao.impl.UserDaoImpl" ></bean><bean id= "with interface-oriented thought programming Userserviceimpl "class=" Com.jbit.fsd.service.impl.UserServiceImpl "><property name=" DAO "ref=" Userdao "> </property> <!--attribute injection--></bean><!--configuration facets--><bean id= "servicelogging" class= " Com.jbit.fsd.aop.ServiceLoging "></bean><aop:config><!--configuration pointcut--><aop:pointcut expression = "Execution (public void AddUser (Com.jbit.fsd.entity.User))" id= "Servicepointcut"/><!--to draw facets and pointcuts together-- <aop:aspect ref= "servicelogging" ><aop:before method= "Beforeservice" pointcut-ref= "ServicePointcut"/> </aop:aspect></aop:config></beans>
8.main method Test:
Package Com.jbit.fsd.test;import Java.util.list;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.jbit.fsd.dao.userdao;import Com.jbit.fsd.entity.user;import Com.jbit.fsd.printer.printer;import Com.jbit.fsd.service.userservice;import Com.jbit.fsd.service.impl.userserviceimpl;public class Test {/** * @param args */public static void main (string[] args) {A Pplicationcontext ac=new classpathxmlapplicationcontext ("Applicationcontext.xml"); UserService dao= (UserService) Ac.getbean ("Userserviceimpl");d Ao.adduser (New User ());}}
Description
1. In the. xml file, you need to add an AOP namespace to import the labels related to the AOP configuration.
2.AOP related configuration in the <aop:config> tab, the Pointcut is configured in the <aop:pointcut> tab.
3.execution is the identifier for the pointcut, the parentheses are the expressions for the pointcut, and the methods that need to be enhanced are configured.
4. Pointcut expressions commonly used several fuzzy matching methods:
>public * AddUser (Com.able.entity.User), "*" means the configuration of all types of return values.
>public void * (Com.able.entity.User), "*" stands for matching all method names.
>public void AddUser (..), "..." Represents the number and type of matches for all parameters.
> * Com.able.service.*.* (..), which represents all methods that match all the classes under the Com.able.service package.
> * Com.able.service. . * (), which represents all methods that match the Com.able.service package and all classes under the sub-package.
III. Introduction to Enhanced processing types
1. Front-mounted enhancement processing
Features: weaving the enhancement process before the target method.
<aop:before method= "Beforeservice" poontcut-ref= "Servicepointcut"/>
If you want to get information about pointcuts in this method, use the following method:
Package Com.jbit.fsd.aop;import Org.apache.commons.logging.log;import org.apache.commons.logging.LogFactory; Import Org.aspectj.lang.joinpoint;public class Serviceloging {private log log = Logfactory.getlog (This.getclass ()); public void Beforeservice (Joinpoint joinpoint) {System.out.println ("AOP method called"); SYSTEM.OUT.PRINTLN ("Connection point object:" +joinpoint.gettarget (). GetClass (). Getsimplename ()); SYSTEM.OUT.PRINTLN ("Connection point method:" +joinpoint.getsignature ()); SYSTEM.OUT.PRINTLN ("Connection point method parameter:" +joinpoint.getargs () [0]);}}
2. Post-Enhancement processing
Features: Weaving enhanced processing after the target method has been performed normally (no exception occurs).
<aop:after-returning method= "afterreturning" pointcut-ref= "Servicepointcut"/>
If you need to get the return value, add returning= "ReturnVal"
<aop:after-returning method= "aft" pointcut-ref= "Ser" returning= "ReturnVal"/>
public void Afterservice (Object returnval) {System.out.println (returnval);}
3. Exception Enhancement processing
Features: Weaving enhanced processing after an anomaly in the target method has occurred.
<aop:after-throwing mehod= "" pointcut-ref= "" throwing = "ex"/>
Add throwing= "Ex" If you need to get exception object
public void afterthrowing (Exception ex) {System.out.println (Ex.getmessage ());}
4. Final enhancement processing
Features: Regardless of whether the method is thrown out of the abnormal, will be in the end of the target method weaving such as enhanced processing, similar and finally.
<aop:after method= "after" pointcut-ref= "Servicepointcut"/>
5. Surround Enhancement processing
Features: Both before and after the target method can be woven into the enhanced treatment.
<aop:around method= "" pointcut-ref= ""/>
Public Boolean Around (Proceedingjoinpoint pjp) throws Throwable{system.out.println ("parameters of the target method:" +pjp.getargs () [0]); Boolean B = Null;if (true) {b = (Boolean) pjp.proceed (Pjp.getargs ());} return b;}
Iv. simplifying AOP configuration with ASPECTJ
Spring's AOP configuration is often in two ways:
> Implement simple AOP Configuration by schema form, which is how the above case is used.
> simplifies AOP configuration with annotation.
ASPECTJ is a facet-oriented framework, and ASPECTJ defines the AOP syntax.
Use @aspectj must use jdk5.0 or later.
Steps:
1. Write the business class (same as the method above).
2. Write the Slice class.
Package Com.jbit.ssh.aop;import Org.aspectj.lang.annotation.after;import Org.aspectj.lang.annotation.Aspect; Import Org.aspectj.lang.annotation.Before; @Aspect //1. Mark a slice with annotations public class Aspecttest {@Before ("Execution (* Com.jbit.ssh.service. *.*(..))") 2. Defining pointcuts and enhanced types (tangent expressions) public void Ba () { //3. Enhanced processing Fun 4. Configure XmlSystem.out.println ("Pre-enhanced-------");} @After ("Execution (* com.jbit.ssh.service). *.*(..))") public void aa () {System.out.println ("post-enhancement------"); /** * @before represents the predecessor enhancement * @AfterReturning: Represents the post-enhancement * @Around: Represents the surround enhancement processing * @AfterThrowing: Represents exception enhancement Processing * @After: Indicates final enhancement processing */}
3. Write a configuration file to implement AOP
<?xml version= "1.0" encoding= "UTF-8"?><!---Application context definition for Jpetstore's business layer. -Contains bean references to the transaction manager and to the DAOs in-dataaccesscontext-local/jta.xml (see web. xml) "Contextconfiglocation"). --><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"xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:p= "http://www.springframework.org/schema/p" xmlns: context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/ Schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsdHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-2.5.xsdHttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <!-- 4. Drive--><aop:aspectj-autoproxy/><bean class= "Com.jbit.ssh.aop.AspectTest" based on @aspectj facets ></bean ></beans>
The AOP of Spring core concept