Spring_AOP_Annotation use Aspect to implement dynamic proxy, springaopaspect

Source: Internet
Author: User

Spring_AOP_Annotation use Aspect to implement dynamic proxy, springaopaspect

Spring_aop_annotation implementation:

1.1 Add the aop schema to beans. xml.

1.2 Enable Automatic Retrieval of aop in xml

<aop:aspectj-autoproxy/>

1.3 create a class to implement dynamic proxy

1.4 import the aspectj package. Spring uses the aspect package to implement AOP. Therefore, you need to import this package.

Maven pom. xml:

<dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.6.8</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjrt</artifactId><version>1.6.8</version></dependency><dependency><groupId>aopalliance</groupId><artifactId>aopalliance</artifactId><version>1.0</version></dependency>

1.5 Use @ Aspect to declare this class as a face-cutting class.

// Let this face-cutting class be managed by Spring @ Component ("logAspect") // declare this is a face-cutting class @ Aspectpublic class LogAspect {//...... <span style = "font-family: FangSong_GB2312;" >}</span>


1.6 Add the PointCut description on the corresponding crosstab point

Execution (* com. spring. dao. *. add *(..)) * The first * indicates any return value * The second * Indicates com. spring. all classes in the dao package * Third * indicate all methods starting with add *(..) any Parameter

1.7 if you want to obtain the relevant call information, you can pass it through joinPoint
/*** Execute * execution (* com. spring. dao. *. add *(..)) the first * indicates any return value * The second * Indicates com. spring. the third * of all classes in the dao package indicates all methods starting with "add (..) any parameter */@ Before ("execution (* com. spring. dao. *. add *(..)) | "+" execution (* com. spring. dao. *. update *(..)) | "+" execution (* com. spring. dao. *. delete *(..)) ") public void logStart (JoinPoint jp) {// get the execution object System. out. println (jp. getTarget (); // obtain the execution method System. out. println (jp. getSignature (). getName (); Logger.info ("add logs before method execution, from LogAspect ");}

Specific implementation code:

XML

<? 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: context = "http://www.springframework.org/schema/context" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemaLocation = "http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp://www.springframework.org/schema/beans http: // ww Export springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd "> <! -- Enable Spring's Annotation support --> <context: annotation-config/> <! -- Set which packages Spring uses to find Annotation --> <context: component-scan base-package = "com. spring"/> <! -- Enable Annotation-based Automatic aop proxy --> <aop: aspectj-autoproxy/> </beans>

LogAspect
Package com. spring. proxy; import org. aspectj. lang. joinPoint; 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. springframework. stereotype. component; // Let this partition class be managed by Spring @ Component ("logAspect ") // declare that this is a face-cutting class @ Aspectpublic class LogAspect {/*** execute * execution (* com. spring. dao. *. add *(..)) the first * indicates any return value * The second * Indicates com. spring. the third * of all classes in the dao package indicates all methods starting with "add (..) any parameter */@ Before ("execution (* com. spring. dao. *. add *(..)) | "+" execution (* com. spring. dao. *. update *(..)) | "+" execution (* com. spring. dao. *. delete *(..)) ") public void logStart (JoinPoint jp) {// get the execution object System. out. println (jp. getTarget (); // obtain the execution method System. out. println (jp. getSignature (). getName (); Logger.info ("add logs before method execution, from LogAspect ");} /*** run * @ param jp */@ After ("execution (* com. spring. dao. *. add *(..)) | "+" execution (* com. spring. dao. *. update *(..)) | "+" execution (* com. spring. dao. *. delete *(..)) ") public void logEnd (JoinPoint jp) {// get the execution object System. out. println (jp. getTarget (); // obtain the execution method System. out. println (jp. getSignature (). getName (); Logger.info ("add logs after method execution, from LogAspect ");} /*** execute * @ param pjp * @ throws Throwable */@ Around ("execution (* com. spring. dao. *. add *(..)) | "+" execution (* com. spring. dao. *. update *(..)) | "+" execution (* com. spring. dao. *. delete *(..)) ") public void logAround (ProceedingJoinPoint pjp) throws Throwable {Logger.info (" start to add logs to Around from LogAspect "); // run the program pjp. proceed (); Logger.info ("end Around ");}}

UserService class
Package com. spring. service; import javax. annotation. resource; import org. springframework. stereotype. component; import org. springframework. stereotype. service; import com. spring. dao. IUserDao; import com. spring. model. user; // @ Component (value = "userService") @ Service ("userService") // The business layer uses @ Service to inject public class UserService implements IUserService {private IUserDao userDao; public IUserDao getUserDao () {return userDao;} // injection by name by default. @ Inject is provided in JSR330. // @ Resource (name = "userProxyDao ") // use the proxy class to inject // @ Resource (name = "userDynamicDao") @ Resource (name = "userDao") // aspect public void setUserDao (IUserDao userDao) {this. userDao = userDao;} @ Overridepublic void add (User user) {userDao. add (user) ;}@ Overridepublic void delete (int id) {userDao. delete (id) ;}@ Overridepublic User load (int id) {return userDao. load (id );}}

Test class and test result:



Several methods for implementing Spring AOP applications

Spring has three methods for developing aop applications: Spring 1.2 implements aop through ProxyFactoryBean, that is, dynamic proxy. Aspect must inherit MethodBeforeAdvice, MethodAfterAdvice, and so on. <! -- Proxy object --> <bean id = "man" class = "Man">
<Property name = "name">
<Value type = "java. lang. String"> JOHN </value>
</Property>
</Bean> <! -- Inherits the Aspect of the MethodBeforeAdvice class->
<Bean id = "fbi" class = "FBI"/>
<Bean id = "civilian"
Class = "org. springframework. aop. framework. ProxyFactoryBean">
<Property name = "target">
<Ref bean = "man"/>
</Property> <property name = "interceptorNames">
<List>
<Value> fbi </value>
</List>
</Property>
</Bean> 2: The FBI class is required for Spring 2.0 AOP applications, and it does not need to implement some interfaces. public class FBI {
Public void before (JoinPoint point ){
Man man = (Man) point. getTarget ();
System. err. println ("FBI found" + man. getName () + "in progress" +
Point. getSignature (). getName () + "activity. ");
}
} Note that the method before (JoinPoint) in this class can have any method name and include a JoinPoint class.
You can also write before () directly without parameters. However, this JoinPoint object brings
Information related to this method call, including method parameters and target objects.
Will carry it.
The next step is to test the class code, which is almost no different from the previous one, but now the direct access to man
This bean. <Beans xmlns = "www.springframework.org/schema/beans"
Xmlns: xsi = "... the remaining full text>
 
What is the use of the dynamic proxy of the Spring framework?

Decoupling and. It also improves development efficiency. Easy to modify.
For example, a piece of log recording code. Loger. log ("some mothed invoke at" + new Date (); there is no difficulty. But all your methods. Copy them all? That is too unreliable.
Well. This is the proxy mode in Java mode. You can take a look. Look at that. You will know the proxy of spring. Well. Spring Proxy has two mechanisms: one is jdk Proxy and the other is cglib, which is implemented based on integration. Well. That is, super uses the rewrite method. Then add super. thisMethod () to the rewrite method ();
If the coupling degree is too high, it will bring a lot of hate and trouble to your program upgrade in the future. Well. To be honest. Well. Your project will never change. Therefore, we can ignore this coupling problem. However, the jdk is upgraded. There are other frameworks. Technical upgrade. It will cause problems to your system. And upgrade space. Therefore, we have been doing this to reduce coupling.

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.