"The Path to SSH" Spring's AOP is layered in-depth-using annotations to complete AOP (vii)

Source: Internet
Author: User
Tags throwable

Previous Blog "The Path to SSH" Spring's AOP Layer-by-step--AOP basic principle (vi), we introduce the basic principles of AOP, and the types of 5 kinds of notifications,

Two ways to configure AOP: XML configuration and AspectJ annotation methods.

In this article we use annotations to implement an AOP, so let's take a look at the project's directory first.


We are using the JDK proxy, so we first attach the interface and implementation class code:

package Com.tgb.spring;public interface Usermanager {public void AddUser (String username,string password);p ublic void Deluser (int userid);p ublic String finduserbyid (int userid);p ublic void modifyuser (int userid,string username,string password);} 
Package Com.tgb.spring;public class Usermanagerimpl implements Usermanager {@Overridepublic void AddUser (String UserName, String password) {System.out.println ("----usermanagerimpl.add ()----");} @Overridepublic void Deluser (int userId) {System.out.println ("----usermanagerimpl.deluser ()----"); @Overridepublic String Finduserbyid (int userId) {System.out.println ("----Usermanagerimpl.finduserbyid ()----"); UserId <= 0) {throw new IllegalArgumentException ("The user does not exist");} return "Jiuqiyuliang";} @Overridepublic void ModifyUser (int userId, string userName, string password) {System.out.println ("---- Usermanagerimpl.modifyuser ()----");}}
The above code is the same as what we usually write, the key to see our section class, the same, the slice class can be changed to security detection and log management and so on:
Package Com.tgb.spring;import Org.aspectj.lang.joinpoint;import Org.aspectj.lang.proceedingjoinpoint;import Org.aspectj.lang.annotation.after;import Org.aspectj.lang.annotation.afterreturning;import Org.aspectj.lang.annotation.afterthrowing;import Org.aspectj.lang.annotation.around;import Org.aspectj.lang.annotation.aspect;import Org.aspectj.lang.annotation.before;import Org.aspectj.lang.annotation.Pointcut; @Aspectpublic class Aspectjadvice {/** * Pointcut * define Pointcut, The name of the Pointcut is Aspectjmethod (), this method does not return a value and the parameter * The method is an identity, does not call */@Pointcut ("Execution (* find* (..))") private void Aspectjmethod () {};/** * before * is executed before the core business execution and cannot prevent calls from the core business. * @param joinpoint */@Before ("Aspectjmethod ()") public void Dobefore (Joinpoint joinpoint) {System.out.println ("----- Dobefore.invoke-----"); System.out.println ("Do some security judgments and so on before executing the core business logic"); System.out.println ("Can get what you need through Joinpoint"); SYSTEM.OUT.PRINTLN ("-----End of Dobefore ()------");} /** * Around * Manual control calls the core business logic, as well as pre-and post-call processing, * * Note: When the core business throws an exception, immediately exits and turnsAfteradvice * Execute Afteradvice and go to Throwingadvice * @param PJP * @return * @throws throwable */@Around (value = "Aspectjmetho D () ") Public Object Doaround (Proceedingjoinpoint pjp) throws Throwable {System.out.println ("-----doaround.invoke----- "); System.out.println ("Can do things like before here");//Call Core Logic Object RetVal = Pjp.proceed (); System.out.println ("Things like after" can be done here);  SYSTEM.OUT.PRINTLN ("-----End of Doaround ()------"); return retVal;} /** * after * core business logic exits (including normal execution end and exception exit), execute this advice * @param joinpoint */@After (value = "Aspectjmethod ()") public void DoA fter (Joinpoint joinpoint) {System.out.println ("-----doafter.invoke-----"); System.out.println ("Do some logging operations and so on after executing the core business logic"); System.out.println ("Can get what you need through Joinpoint");  SYSTEM.OUT.PRINTLN ("-----End of Doafter ()------");} /** * afterreturning * core business logic call after normal exit, regardless of whether there is a return value, after the normal exit, execute this advice * @param joinpoint */@AfterReturning (value = "Aspectjmet Hod () ", returning =" RetVal ") public void Doreturn (Joinpoint joinpoint, String retVal) {SysteM.OUT.PRINTLN ("-----doreturn (). Invoke-----"); System.out.println ("Return Value:" + retVal); System.out.println ("The return value can be further processed here"); System.out.println ("Can get what you need through Joinpoint"); SYSTEM.OUT.PRINTLN ("-----End of Doreturn ()------");} /** * Core business logic call after exception exit, execute this advice, handle error message * Note: execution order after around advice * @param joinpoint * @param ex */@AfterThrowing (value = "Aspectjmethod ()", throwing = "ex") public void dothrowing (Joinpoint joinpoint, Exception ex) {System.out.println ("---- -dothrowing (). Invoke-----"); SYSTEM.OUT.PRINTLN ("error message:" +ex.getmessage ()); System.out.println ("Here is intended to perform core business logic errors, catch exceptions, and can do some logging operations, etc."); System.out.println ("Can get what you need through Joinpoint");  SYSTEM.OUT.PRINTLN ("-----End of dothrowing ()------"); }  }
after we have finished configuring the facets class, we also need to combine spring's IOC and AOP:
<?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" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans http:/ /www.springframework.org/schema/beans/spring-beans-4.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www. Springframework.org/schema/aop/spring-aop-4.1.xsd Http://www.springframework.org/schema/tx Http://www.springfram Ework.org/schema/tx/spring-tx-4.1.xsd "><!--enable spring for @aspectj aspects-based configuration support--&GT;&LT;AOP: Aspectj-autoproxy></aop:aspectj-autoproxy><bean id= "Usermanager" class= " Com.tgb.spring.UserManagerImpl "></bean><bean id=" Aspectjadvice "class=" Com.tgb.spring.AspectJAdvice " ></bean></beans>
when all is done, the most important step is to write the client and test it to see if it matches the results we expected.
Package Com.tgb.spring;import Org.springframework.beans.factory.beanfactory;import Org.springframework.context.support.classpathxmlapplicationcontext;public class Client {public static void main ( String[] args) {Beanfactory factory = new Classpathxmlapplicationcontext ("Applicationcontext.xml"); Usermanager Usermanager = (usermanager) factory.getbean ("Usermanager");//Can find Zhang San Usermanager.finduserbyid (1); System.out.println ("===== i = = = = Division = = Cut = = Line ====="); try {//Cannot find the data, will throw an exception, Exceptions are captured by Afterthrowingadvice Usermanager.finduserbyid (0);} catch (IllegalArgumentException e) {}}}

Run Results

Normal operation, no exception thrown (i) abnormal operation, with exception thrown (ii)


The purpose of the above two graphs is to give you a clearer picture of the advice five types of running order.


Using annotations is a good way to help us understand the principles of AOP, and if the principles of AOP are not particularly clear, take a look at the diagram of the previous blog post. Let's use XML to implement AOP again.

SSH Advanced path The AOP of spring is layered in depth--using annotations to complete AOP (vii)

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.