About spring AOP aspect-oriented programming __ programming

Source: Internet
Author: User
Tags aop

AOP, the idea of horizontal programming of the business is really good. A simple practical application:

In the process of doing the project, did a landing function, the project after this, need to log in after the user log management, that is, login successful user information exists in the database.


This time do not go back to the source code, in the login function inside to write something, using the principle of AOP to intercept the large expansion of the program's scalability.


Project Architecture Springmvc + Spring


As anyone familiar with this architecture project knows, controller is managed by the *-servlet.xml (SPRINGMVC) file, and the service layer is managed by the Application.xml (Spring) file.


AOP is configured in four ways, typically 2, 1. Annotation mode 2. How to configure a file


I like to use configuration files in the way.

Let's start with AOP programming for service.

Service layer:

Interface:

Package com.lgy.service;

Public interface Sleepable {
	void sleep ();
	int eat ();
	int play ();
}

Realize:

Package com.lgy.service;

Import Org.springframework.stereotype.Service;

@Service public
class Human implements sleepable {
	@Override public
	Void Sleep () {
		System.out.println ( "People are sleeping");
	}

	@Override public
	int Eat () {
		System.out.println ("Dog in Eat");
		return 1;
	}

	@Override Public
	int Play () {
		System.out.println ("Play Baskball");
		return 1;
	}

}

Description: Three methods, of which 2 methods have return values.


The inserted objects are as follows:

Package COM.LGY.AOP;

Import Org.aspectj.lang.ProceedingJoinPoint;

public class Sleephelper {public
	 void Aftersleep () {
	     System.out.println) ("Dress up when you wake up.") ");
	 }
	 
	 Proceedingjoinpoint only in around public
	 Object aroundeat (Proceedingjoinpoint joinpoint) throws Throwable {
		 System.out.println ("Prior to Execution");
		 Object result = Joinpoint.proceed ();   The target object executes
		 System.out.println ("after Execution");
		 return result;
	 }
	 
	 public void Afterreturn () {
		 System.out.println (after execution);
	 }

Three methods that correspond to the three methods of the slice.




Beans.xml (SPRING-AOP core configuration file):

<!--configure objects that need to be-->
<bean id= "Sleephelper" class= "Com.lgy.aop.SleepHelper" ></bean>


<aop:config>
    <aop:aspect ref= "Sleephelper" >
	<!--insert--> <aop:after method=
	    " Aftersleep "pointcut=" Execution (* com.lgy.service.*.sleep (..)) " />
	    <!--around gets the return value--> <aop:around method= "Aroundeat" pointcut=
	    (* execution. Eat (..)) " --> <aop:after-returning method= "Afterreturn" pointcut= "execution"
	    after/> <!--return
	    (* Com.lgy.service.*.play (..)) " />
    </aop:aspect>
</aop:config>

The insertion order for methods is as follows:

<aop:after method= "" The/> Slice method is completed after inserting
<aop:after-returning method= "" The/> Slice method completes the return value after inserting
<aop:after-throwing method= ""/> Slice method inserts when an exception is thrown
<aop:around method= ""/> Slice method inserts before and after the start (actually customization)
<aop:before method= ""/> Slice method inserts before starting


If wrapping is used, you can add Proceedingjoinpoint to the method parameter Joinpoint
The object Joinpoint.process () can execute the slice method and get the return value.

The test code is as follows:

/**
Recommendations
* If the target object has no return:
* On Demand
* 1. If the method has return
* Use AOP After-return or around
* 2. If the method does not return
* Then use the AOP or before
*/

Package AOP;

Import Javax.annotation.Resource;

Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.test.context.ContextConfiguration;
Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

Import com.lgy.service.Sleepable;

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration (locations = {"Classpath:/beans.xml"})
public class Aoptest {
	@Resource (name= "Human")
	private sleepable sleepable;
	@Test public
	void Humafter () {
		sleepable.sleep ();
	}
	
	@Test public
	void Humaround () {
		int eat = Sleepable.eat ();
		System.out.println (eat);  The final return value
	}
	
	@Test public
	void Humafterreturn () {
		int i = Sleepable.play ()
		, according to around's slice method; System.out.println (i);  Final return value} based on around slice
	method



The above is to the service layer code for slicing programming---------------------------------------------------------------------------------------------------- ---------------

One thing that is different in the controller layer is the configuration location for AOP. Because the Contorller layer is SPRINGMVC for management, service layer is spring to manage, and then produce different proxy class, AOP production agent class has 2 kinds of ways 1.JDK dynamic Agent 2.cglib Proxy method has the difference is the former can only interface agent, The latter can proxy the class, and if the target object does not implement an interface, the Cglib proxy is used by default.

Therefore, it is not possible to configure AOP in Bean.xml, and you need to configure AOP in *-servlet.xml.

Controller layer for cutting plane programming:

Code for the controller layer:

It's also a slice object.

Package Com.lgy.controller;

Import Javax.annotation.Resource;

Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;

Import com.lgy.service.Sleepable;

@Controller
@RequestMapping ("/AOP") public
class Aopcontroller {
	@Resource (name= "Human")
	private Sleepable sleepable;
	
	@RequestMapping ("/hello") public
	String Hello () {
		System.out.println ("Hello World");
		return "Hello";
	}


The inserted objects are as follows:

Package COM.LGY.AOP;

public class Hellohelp {public
	void Hellobefore () {
		System.out.println ("AOP  HELLP  before ...");
	}
}

*.servlet.xml File Contents:

<?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:co
       ntext= "Http://www.springframework.org/schema/context" xmlns:mvc= "Http://www.springframework.org/schema/mvc" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans /spring-beans.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/s Pring-aop.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/contex T/spring-context.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema
					   
	/mvc/spring-mvc-3.2.xsd "> <!--use cglib proxy <aop:aspectj-autoproxy proxy-target-class=" true "/>--> <!--automatic scanning and scanning only @contrOller--> <context:component-scan base-package= "Com.lgy" use-default-filters= "false" > <context: Include-filter type= "Annotation" expression= "Org.springframework.stereotype.Controller"/> </context:  
            Component-scan> <!--annotations effective JSON conversion--> <mvc:annotation-driven> <mvc:message-converters>  <bean class= "Org.springframework.http.converter.StringHttpMessageConverter" > <property name = "Supportedmediatypes" > <list> <value>text/plain;charset=UTF-8</value> &LT;/LIST&G
				T
	
	</property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!--file Upload view parser, SPRINGMVC to this ID name multipartresolver--> <bean id= "Multipartresolver" Org.springframework.web.multipart.commons.CommonsMultipartResolver "/> <!--Configure a static resource--> <!--configuration View Parser
    ; <bean class= "org.springframework.web.servlet.view.iNternalresourceviewresolver "> <property name=" prefix "value="/web-inf/"></property> <propert 
	    Y name= "suffix" value= ". jsp" ></property> </bean> <!--controller--> <aop:config> <aop:aspect ref= "Hellohelp" > <!--after inserting--> <aop:before method= "Hellobefore" pointcut= "E Xecution (* Com.lgy.controller.*.hello (..)) " /> </aop:aspect> </aop:config> </beans>

The hellohelp in ref can be configured in the Bean.xml file.

Execute localhost::8080/project name/aop/hello

All the tests passed.

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.