Two kinds of implementation of aspect-oriented programming __ programming

Source: Internet
Author: User
Tags aop throwable

1, face-oriented definition of its own Baidu

2, face-oriented programming of the application of the scene of their own imagination, is probably the log and other places

3, the above two words is basically nonsense


Implementation method One, declaring the slice in XML

1. Write an original class

Package Com.hsb.beans;

Import org.springframework.stereotype.Repository;

@Repository public
class perform {public
	void Show () {System.out.println ("Message from
		perform.show ()");
	}
}
The show () method in this example is the pointcut. In a large project, many pointcuts form sections that actually make up a surface for something common.
2, write a slice class

Package COM.HSB.AOP;

Import Org.aspectj.lang.ProceedingJoinPoint;

public class Audience {public
	void Beforeshow () {
		System.out.println (' Message from Beforeshow ');
	}
	public void Aftershow () {
		System.out.println (' Message from Aftershow ');
	}
	public void Around (Proceedingjoinpoint joinpoint) {
		System.out.println ("Message from Start around");
		Long start = System.currenttimemillis ();
		try {
			joinpoint.proceed ();
		} catch (Throwable e) {
			e.printstacktrace ();
		}
		Long end = System.currenttimemillis ();
		SYSTEM.OUT.PRINTLN ("Message from end around total:" + (End-start) + "MS");
	}

Notice the Joinpoint.proceed () in the code, which is the actual call to the Pointcut method, which is the show () in this example. If the around notification is defined in the slice class, the notification must be added, otherwise the Tangency method will not be invoked. Here should be a hole, be sure to remember, so that the bugs are nowhere to be found in the back.


3. Configure XML

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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:context=" Http://www.springframework.org/schema/context "xsi: schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/sche   
                        Ma/beans/spring-beans-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/s Chema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd H Ttp://www.springframework.org/schema/context Http://www.springframework.org/schema/context/spri Ng-context-3.0.xsd "default-lazy-init=" true ">Context:component-scan base-package= "Com.hsb.beans"/> <bean id= "Audience" class= "Com.hsb.aop.Audience"/> <aop:config> <aop:aspect ref= "Audience" > <aop:pointcut expression= "Execution (* com.hsb.beans.Perform
				. Show (..)) " Id= "Performance"/> <aop:before method= "beforeshow" pointcut-ref= "Performance"/> "<aop:after method=" aft Ershow "pointcut-ref=" Performance "/> <aop:around method=" Around "pointcut-ref=" performance "/> </aop:asp Ect> </aop:config> </beans>
Note that the above <bean id= "audience" class= "com.hsb.aop.Audience"/> The slice life as a bean, and <aop:config></aop:config The bean is referenced in the > statement. Briefly explain the meaning of each sentence in the <aop:config> statement. When configuring a declaration, be sure to use English characters to configure, or you will report a lot of strange mistakes, roughly that the cut is not used or anything else.

<aop:pointcut expression= "Execution (* com.hsb.beans.Perform.show (..))"
				Id= "Performance"/>
A pointcut (pointcut) is declared, and the notification declared later is referenced.

Notice a total of five species are <aop:before/>, <aop:after/>, <aop:after-returning/>, <aop:after-throwing/>, < Aop:around/>. The application scenario is probably understood by its literal meaning, and around has already said, identifying the pointcut position and doing some work before and after the tangent point.

4, testing

Package Com.hsb.dao;

Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.test.context.ContextConfiguration;
Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

Import Com.hsb.beans.Perform;

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration ({"Classpath*:* */applicationcontext.xml", " classpath*:* */springmvc-servlet.xml "}) public
class Performtests {
	@Autowired
	private perform perform;

	@Test public
	void Testshow () {
		perform.show ();
	}

}
The code above uses automatic injection to generate a perform instance that invokes the Pointcut method Show () in the test method.

5, Console printing results

September 05, 2016 9:54:03 pm Org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadbeandefinitions
Information: Loading XML Bean definitions from file [D:\PractiseForWork\WorkSpace\HelloMaven\target\classes\ Applicationcontext.xml]
September 05, 2016 9:54:04 PM Org.springframework.context.support.AbstractApplicationContext Preparerefresh
information: refreshing org.springframework.context.support.genericapplicationcontext@6e3c1e69:startup Date [Mon Sep 21:54:04 CST 2016]; Root of context hierarchy message from
beforeshow to
Start around message from
perform.show ()
Around total:38 MS Message from
aftershow
From the console print result, we can guess the specific usage of five kinds of notifications


6, MAVEN project must add dependencies

                <dependency>
			<groupId>org.aspectj</groupId>
			<artifactid>aspectjrt</ artifactid>
			<version>1.6.12</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			< Version>1.6.12</version>
		</dependency>
If you do not add the above dependencies, you will most likely test the error.



Implementation mode two, annotated slice

1. Write an original class

Package Com.hsb.beans;

Import org.springframework.stereotype.Repository;

@Repository public
class perform {public
	void Show () {
		System.out.println ()-Perform.show () ");
	}
}
2, write a slice class

Package COM.HSB.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;

Import org.springframework.stereotype.Component;
	@Aspect @Component public class Audience {@Pointcut ("Execution (* com.hsb.beans.Perform.show (..))") public void Performance () {} @Before (' Performance () ') public void Beforeshow () {System.out.println
	Eforeshow ");
	@After ("Performance ()") is public void aftershow () {System.out.println ("the Message from Aftershow");  @Around ("Performance ()") public void Around (Proceedingjoinpoint joinpoint) {System.out.println ("message from Start
		Around ");
		Long start = System.currenttimemillis ();
		try {joinpoint.proceed ();
		catch (Throwable e) {e.printstacktrace ();
		Long end = System.currenttimemillis (); System.out.println ("Around total: "+ (End-start) +" MS ");
 }
}
@Aspect declare this class as a slice class, @Component place such a declaration as a bean in the spring container, @Pointcut declare the following performance as a pointcut, and associate the Show () method in perform. Execution (* com.hsb.beans.Perform.show (..)) When this method is executed, the return value is ignored, and the parameter type and number are ignored. It can also be shortened to match the appropriate method, for example, to match all the methods of the Perform class is com.hsb.beans.perform.*.

3. Configure XML

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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:context=" Http://www.springframework.org/schema/context "xsi: schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/sche   
                        Ma/beans/spring-beans-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/s Chema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd H Ttp://www.springframework.org/schema/context Http://www.springframework.org/schema/context/spri Ng-context-3.0.xsd "default-lazy-init=" true ">; Context:component-scan base-package= "com.hsb.*"/> <aop:aspectj-autoproxy proxy-target-class= "true"/> </beans>
You can see that the <aop:config/> Declaration is not used here, but instead uses the <aop:aspectj-autoproxy proxy-target-class= "true"/>. This means automatically creating a Annotationawareaspectjautoproxycreator class in the spring context that automatically proxies some beans, The methods of these beans need to match the pointcuts defined in the bean using the @aspect annotation, which are defined using the @pointcut annotation. Proxy-target-class= "true" means using a cglib library using a class based proxy and, if False, using an interface-based proxy from the JDK

4, testing

Package Com.hsb.dao;

Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.test.context.ContextConfiguration;
Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

Import Com.hsb.beans.Perform;

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration ({"Classpath*:* */applicationcontext.xml", " classpath*:* */springmvc-servlet.xml "}) public
class Performtests {
	@Autowired
	private perform perform;

	@Test public
	void Testshow () {
		perform.show ();
	}

}

5, Console printing results

September 05, 2016 10:24:46 pm Org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadbeandefinitions
Information: Loading XML Bean definitions from file [D:\PractiseForWork\WorkSpace\HelloMaven\target\classes\ Applicationcontext.xml]
September 05, 2016 10:24:47 PM Org.springframework.context.support.AbstractApplicationContext Preparerefresh
information: refreshing org.springframework.context.support.genericapplicationcontext@6e3c1e69:startup Date [Mon Sep 22:24:47 CST 2016]; Root of context hierarchy message from Start to around message from
beforeshow to
perform.show ()
Around total:39 MS Message from
aftershow

As shown above, it is exactly the same effect. It can be seen that the use of annotations reduces a lot of work, not error-prone, the coupling between the various components decreased. Just think, if a large project has many facets, pointcuts, if all go to the XML configuration, will be a very hard work, but if you use annotations can do very little work to do it all.



PostScript one, use the annotation must use @component or @repository, @Controller, @Service one to declare, put the slice class into the spring container, or go to XML to write a bean explicitly, otherwise it will be an error, Unable to implement slice function.


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.