SSH Deep Adventures (10) AOP principles and related concepts Learning +ASPECTJ annotation mode configuring Spring AOP

Source: Internet
Author: User

AOP (Aspect oriented programming). is a technology for cutting-plane programming. AOP is based on the IOC Foundation. is a deliberate addition to OOP.


The reason why AOP can be widely used is that it splits the application system into 2 parts: core business logic (concerns) and horizontal general logic, which is called crosscutting enterprise concerns. For example, all medium-to-large applications involve persistent management (persistent), transaction management (Transaction Management), Rights Management (Privilege Management), Log management (Logging) and debug Management (Debugging).


Using AOP technology allows developers to focus solely on the core business, while the general logic uses AOP technology to cut in horizontally. Handling these general-purpose logic by hand will make the task simple and clear, and improve the efficiency of development and commissioning.


using AOP, we should pay attention to the functionality of crosscutting. That is, the abstraction of independent services. Modularity allows us to change the way we used to think vertically, and pay attention to the way of thinking horizontally, and we combine today's system to infer the validation of text boxes, log records, open transactions, open and close databases, and so on. are able to abstract these methods into the form of facets, we just need to be concerned with our business logic. This code is simple, indirect, the development efficiency is greatly improved, more importantly, the reuse efficiency has been greatly improved.


Basic Concepts

to learn about AOP. There are several important basic concepts to understand first:



  • Facets (Aspect) : The modularity of a focus point. This focus implementation may have additional crosscutting across multiple objects. For example, transaction management is a very good example of crosscutting concerns in the Java EE application. Facets are implemented with spring's advisor or interceptor.


  • connection point (Joinpoint) : The point at which the program is running, such as a call to a method or a particular exception being thrown.
  • Notice (Advice) : The action that the AOP framework runs at a particular connection point.

    Various types of notifications include "around", "before", and "throws" notifications. The notification type is discussed in the following.

    Many of the AOP frameworks contain spring as a notification model with interceptors. Maintains an interceptor chain that surrounds the connection point.


  • entry point (Pointcut) : Specifies a collection of connection points to which a notification will be raised.

    The AOP framework must agree with developers to specify Pointcuts. For example, use the regular form.

  • Destination Object (target objects) : An object that includes a connection point, also known as a notified or Proxied object.
  • AOP Agent (AOP proxy) : An AOP framework creates objects, including notifications. In spring, an AOP agent can be a JDK dynamic agent or a cglib agent.
  • Weaving (Weaving) : Assembly aspect to create a notified object.

    This can be done at compile time (for example, with the ASPECTJ compiler), and can be completed at execution time. Spring, like other pure Java AOP frameworks, is woven into execution.


Types of notifications (Advice)in order to comply with various process processing. There are 5 types of notifications that can be used to deal with all aspects of the target approach:
  • before advice : A notification that runs before a connection point (Joinpoint). However, this notification does not prevent the operation before the connection point.
    The ApplicationContext uses <aop:before> elements to declare in <aop:aspect>.
  • After advice : A notification that runs when a connection point exits (whether it is a normal return or an unexpected exit).
    The ApplicationContext uses <aop:after> elements to declare in <aop:aspect>.

  • After Returnadvice : A notification that runs after a connection point has completed normally, and does not contain a case of throwing an exception.
    The ApplicationContext uses <aop:after-returning> elements to declare in <aop:aspect>.
  • Around Advice : A notification that surrounds a connection point. A Dofilter method that resembles the filter in the servlet specification in the Web. The ability to complete the defined behavior before and after the invocation of a method can also choose not to run.


    The ApplicationContext uses <aop:around> elements to declare in <aop:aspect>.

  • afterthrowing Advice : A notification that runs when the method throws an unexpected exit.


    The ApplicationContext uses <aop:after-throwing> elements to declare in <aop:aspect>.

The JDK proxy method used in this paper


ASPECTJ annotation mode to configure AOP. Example Commentary


Securityhandler, this notification class can be switched to security detection, log management, transaction open shutdown, and so on.


<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;" >package Com.bjpowernode.spring;import Org.aspectj.lang.annotation.after;import Org.aspectj.lang.annotation.aspect;import Org.aspectj.lang.annotation.before;import Org.aspectj.lang.annotation.Pointcut; @Aspectpublic class Securityhandler {/** * defines Pointcut. The name of the Pointcut is Addaddmethod (), this method does not return a value and the number of parameters * The method is an identity, does not call */@Pointcut ("Execution (* add* (..))") private void Addaddmethod () {};/** * defines advice, which indicates the pointcut of Joinpoint subscriptions to which our advice applies *///@Before ("Addaddmethod ()") @ After ("Addaddmethod ()") private void CheckSecurity () {System.out.println ("-------checksecurity-------");} </span>

Usermanager interface



<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;" >package Com.bjpowernode.spring;public interface Usermanager {public void AddUser (string username, string password); public void Deluser (int userid);p ublic string Finduserbyid (int userid);p ublic void modifyuser (int userid, String username , String password);} </span>

Usermanagerimpl implementation



<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;" >package Com.bjpowernode.spring;public class Usermanagerimpl implements Usermanager {public void AddUser (String Username, String password) {//checksecurity (); System.out.println ("---------usermanagerimpl.add ()--------");} public void Deluser (int userId) {//checksecurity (); System.out.println ("---------usermanagerimpl.deluser ()--------");} Public String Finduserbyid (int userId) {//checksecurity (); System.out.println ("---------Usermanagerimpl.finduserbyid ()--------"); return "Zhang San";} public void ModifyUser (int userId, string Username, string password) {//checksecurity (); System.out.println ("---------usermanagerimpl.modifyuser ()--------");} private void CheckSecurity () {//system.out.println ("-------checksecurity-------");//}}</span>

The Application-config.xml. Only business logic beans and aspect beans need to be configured. and enable aspect annotations to:


<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;"     ><?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-2.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework.org/schema/aop/spring-aop-2.0.xsd Http://www.springframework.org/schema/tx HTTP://WW W.springframework.org/schema/tx/spring-tx-2.0.xsd "> <!--enable ASPECTJ support for annotation-&LT;AOP: aspectj-autoproxy/> <bean id= "Usermanager" class= "Com.bjpowernode.spring.UserManagerImpl"/><bean id= "Securityhandler" class= "Com.bjpowernode.spring.SecurityHandler"/></beans></span>

Clientclient


<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;" >package Com.bjpowernode.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"); Usermanager.adduser ("Zhang San", "123");}} </span>





Of course, we can use annotations to achieve flexible configuration


<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;" >/** * defines advice. Indicates which pointcut subscriptions our advice applies to on the Joinpoint */@Before ("Addaddmethod ()")//@After ("Addaddmethod ()") private void CheckSecurity () {System.out.println ("-------checksecurity-------");} </span>


Effects after the change:





Summarize

Annotation

Strengths

Save in the class file to reduce maintenance costs.

No tool support required. No parsing required.

compile time can verify correctness, error-checking becomes easy.

 

Disadvantages
to make changes to the configuration item. Have to change the Java file and compile the packaged application again.


In general, the advantage of AOP is that we abstracted public methods, our code, method reusability greatly improved, the implementation of flexible configuration, improve the system reliability.



Next


SSH Deep Adventures (11) AOP principles and related concepts Learn +xml configuration examples (pros and cons of annotation methods)

SSH Deep Adventures (10) AOP principles and related concepts Learning +ASPECTJ annotation mode configuring Spring AOP

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.