Spring AOP Application Example Demo

Source: Internet
Author: User


AOP ( aspect-oriented Programming , aspect-oriented programming), can be said to be OOP ( object-orientedprograming , object-oriented programming) complements and improves. OOP introduces concepts such as encapsulation, inheritance, and polymorphism to create an object hierarchy that simulates a collection of public behavior.


The question of OOP, the complement of AOP


when we need to introduce public behavior to scattered objects, OOP is powerless. In other words,OOP allows you to define relationships from top to bottom, but it is not appropriate to define left-to-right relationships. such as logging capabilities. Log code is often spread horizontally across all object hierarchies, and has nothing to do with the core functionality of the objects it spreads to. This is true for other types of code, such as security, exception handling, and transparent persistence. This irrelevant code scattered around is called crosscutting (cross-cutting) code, and in OOP design, it leads to a lot of duplication of code, rather than the reuse of individual modules.

The so-called "aspect", in a nutshell, is to encapsulate the logic or responsibility that is not related to the business, but for the common invocation of the business module, to reduce the duplication of code in the system, to reduce the coupling between modules, and to facilitate future operability and maintainability.

support for AOP in Spring

SpringinAOPAgent bySpringof theIoCThe container is responsible for generating, managing, and its dependencies are alsoIoCThe container is responsible for management. Therefore,AOPthe agent can directly use the others in the containerBeaninstance as the target, this relationship can beIoCthe container's dependency injection is provided. SpringDefault UsageJavadynamic agents to createAOPAgent,This allows you to create proxies for any instance of the interface. When the class that needs the proxy is not the proxy interface,Springautomatically switches to useCGLIBProxy, can also be forced to useCGLIB.


Programmer Engagement Section


AOP programming is actually a very simple thing. Throughout AOP programming, There are only three parts that require programmer involvement:

Define common business components.

Define Pointcuts, where a pointcut can cross-cut multiple business components.

defining enhanced processing, enhanced processing is AOP A frame is a processing action that is woven into a common business component.

so the AOP the key to programming is defining pointcuts and defining enhanced processing. Once the appropriate pointcuts and enhancements have been defined,theAOP Framework will automatically generate an AOP Proxy, that is: The method of the proxy object = Enhanced processing + method of the object being proxied.

How to use in Spring:

based on Annotation "0 Configuration" mode.

( 1 ) Start annotations, configuration Files Applicationcontext.xml

<!--start support for @aspectj annotations--     <aop:aspectj-autoproxy/><bean id= "user" class= " Com.tgb.spring.aop.IUserImpl "/><bean id=" Check "class=" Com.tgb.spring.aop.CheckUser "/>

( 2 ) Writing slice classes

Package Com.tgb.spring.aop;import Org.aspectj.lang.proceedingjoinpoint;import Org.aspectj.lang.annotation.After; Import Org.aspectj.lang.annotation.around;import Org.aspectj.lang.annotation.aspect;import Org.aspectj.lang.annotation.before;import Org.aspectj.lang.annotation.Pointcut; @Aspect public class CheckUser {@ Pointcut ("Execution (* com.tgb.spring.aop.*.find* (..))") public void CheckUser () {System.out.println ("**************the System was searching information for you****************" );} @Pointcut ("Execution (* com.tgb.spring.aop.*.add* (..))") public void Checkadd () {System.out.println ("**************<< Add User >> checking.....***************");} @Before ("CheckUser ()") public void Beforecheck () {System.out.println (">>>>>>>> Ready to search users ..........");} @After ("CheckUser ()") public void Aftercheck () {System.out.println (">>>>>>>> Search user completed ..........");} @Before ("Checkadd ()") public void Beforeadd () {System.out.println (">>>>>>>>Increase the user-check ing ... ");} @After ("Checkadd ()") public void Afteradd () {System.out.println (">>>>>>>> Add users"-check it out!) No exception was found!.......... ");} Statement Wrapping Notification @Around ("CheckUser ()") Public Object Doaround (Proceedingjoinpoint pjp) throws Throwable {Syst          Em.out.println ("Entry Method---surround notification");          Object o = pjp.proceed ();          System.out.println ("Exit Method---surround notification");      return o; }  }

( 3 ) define the interface

Package Com.tgb.spring.aop;public interface Iuser {public String Finduser (string username);p ublic void AddUser (string username);p ublic void FindAll ();}

( 4 ) defines the implementation

Package Com.tgb.spring.aop;import Java.util.hashmap;import Java.util.map;public class Iuserimpl implements IUser { public static map map = Null;public static void init () {string[] list = {"Lucy", "Tom", "Xiaoming", "Smith", "Hello"}; MAP tmp = new HashMap (), for (int i=0; i<list.length; i++) {tmp.put (list[i], list[i]+ "00");} Map = tmp;} public void AddUser (String username) {init (); Map.put (username, username+ "11"); System.out.println ("--------------" AddUser ":" +username+ "--------------"); System.out.println ("The New List:" +map+ "" ");} public void FindAll () {init (); System.out.println ("---------------" FindAll ":" +map+ "------------------");} public string Finduser (string username) {init (); String Password = "The user was not found"; if (Map.containskey (username)) {password = Map.get (username). toString ();} System.out.println ("-----------------" Finduser "-----------------"); System.out.println ("-----------------Username:" +username+ "-----------------"); System.out.println ("-----------------" Result ": +password+"------------------"); return password;}} 

( 5 ) Test

public class Test {public static void main (String as[]) {beanfactory factory = new Classpathxmlapplicationcontext ("Applica Tioncontext.xml ") iuser user = (Iuser) factory.getbean (" user "); User.findall (); User U = New user (),//u.setusername ("Tom"),//user.finduser (U.getusername ()),/*u.setusername ("haha"); User.adduser ( U.getusername ()); */}}

Execution Result:

Entry Method ---Surround notifications

>>>>>>>> ready to search users ..........

---------------" FindAll ": {smith=smith00, tom=tom00, xiaoming = Xiao Ming xx, lucy=lucy00,hello=hello00}------------------

Exit Method ---Surround notifications

>>>>>>>> Search User Complete ..........

Note: @Before is to execute a piece of logic before the intercepted method executes. @After is to execute a piece of logic after the intercepted method executes. @Around is a logic that can be executed both before and after the intercepted method.

The above is implemented for annotations, so the configuration file is the same, just add the following code to the Applicationcontext.xml:

<!--  <aop:config><aop:pointcut id= "find" expression= "Execution (* com.tgb.spring.aop.*.find* (..))" /><aop:pointcut id= "Add" expression= "Execution (* com.tgb.spring.aop.*.add* (..))"/><aop:aspect id= " CheckUser "ref=" check "><aop:before method=" Beforecheck "pointcut-ref=" find "/><aop:after method=" Aftercheck "pointcut-ref=" find "/></aop:aspect><aop:aspect id=" Checkadd "ref=" Check "><aop:before Method= "Beforeadd" pointcut-ref= "Add"/><aop:after method= "Afteradd" pointcut-ref= "Add"/></aop:aspect ></aop:config>-->

Summary:

The above is a brief introduction of how to use Spring AOP, in the use of the process also deepened our AOP the understanding of thought, in fact AOP is to let us achieve hot plug effect, the next chapter will continue to introduce Spring AOP principle of implementation.

attached: Note the JDK version and the easy-to-use version of Aspectjrt problem




Spring AOP Application Example Demo

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.