The use of XML and annotations for SPRING_AOP

Source: Internet
Author: User
Tags throw exception throwable

Dynamic Agent:

Objective: To enhance the method without changing the source code!

Dynamic agents are divided into two types:
1. The first is an interface-based dynamic agent, which is provided by the JDK
2. Subclass-based Dynamic proxy: Cglib provides: To use a subclass-based dynamic proxy: You must import the Cglib jar package

Attribute: Any method of the object being proxied


SPRING_AOP: summary
AOP (Aspect oriented Programming): tangent-oriented programming

Facets: Additional functional modules relative to the business line
Enhancements to the method without changing the source code of the program

The underlying principle of AOP is dynamic proxy
At the bottom of the AOP, he automatically chooses whether to use a dynamic proxy based on or using subclasses, depending on the code.

What is the benefit of programming with AOP?
1. Simplifying the business code
2. Simple Maintenance

AOP-related terminology
Joinpoint (Connection point): Method of execution
Pointcut (Pointcut): Enhanced method
Advice (Notification/enhancement): Is the additional function module
Front-facing notifications
Post notification
Exception notification
Final Notice
Surround Notifications
Aspect (Tangent):
How to enhance that method
What is the focus of learning about AOP?
1. The focus is on one of the additional functional modules
Configuration of 2.AOP
The third spring AOP development process
Define a slice Class
Common Java class in which the target object is enhanced by one of the methods in this class

2. Configuring AOP
In the XML configuration file in the AOP
I. Give the slice class to spring management

Ii. declaring an AOP configuration
<aop:config>
Iii. Defining pointcuts
Aop:pointcut
IIII. Defining Notification types
<aop:aspect ref = "Reference to slice Class" >
Front-facing notifications
<aop:before method= "The method name of the Slice class pointcut-ref=" pointcut expression is reference "/>
The post-notification <aop:afterrunturning method= The method name of the slice class pointcut-ref= the pointcut expression is a reference to the/>
Exception notification <aop:after-throwing method= "The method name of the Slice class pointcut-ref=" pointcut expression is reference "/>
The final notification <aop:after method= "The method name of the slice class" pointcut-ref= "pointcut expression is reference"/>
Note: Exception notifications are only notified if an exception occurs
</aop:aspect>
Annotation-based AOP configuration (combined with XML)
1. Give the slice class to spring management
2. Replace the configuration of AOP in XML with the form of annotations
3. Use annotations to configure spring's IOC or AOP with support for annotations!

Note: Using annotations to configure AOP and XML configuration AOP has some differences when it comes to post-notification!
Annotation configuration: Is the last to perform the post-notification!

Pure annotation Configuration AOP
1. Declaring the Configuration class
2. Open support for IOC
3. Turn on support for AOP annotations
@EnableAspectJAutoProxy

Development steps and explanation of the code
<!--to spring the slice class
<bean id= "Logger" class= "Cn.itcast.utils.Logger" ></bean>

<!--declaring AOP configuration: namespaces that require AOP (constraints that must be imported into AOP)
Aop:config: Declaring an AOP configuration
-
<aop:config>

<!--defining pointcuts: Defining Enhanced methods
Expression:execution (class modifier Returns the value of the package name.) Package Name ... Class name. Method name (parameter list)
1. Class modifiers can be omitted: return value package name. Package Name ... Class name. Method name (parameter list)
2. The return value can be substituted with the * number: Identify any return value can be
3. The package name can be replaced with the * number, a package requires a *
4. Package Name: Represents this package and any child packages of this package
5. Class names can be substituted with *, representing any class
6. Method names can use the * proxy, representing any method
7. Parameter categories can be used: Represents arbitrary parameters

This notation *.. * * (..) Not recommended

-
<aop:pointcut expression= "Execution (* Cn.itcast.service.impl. *.*(..))" Id= "PT"/>



<!--configuration Facets
Aop:aspect
Ref: A reference to a slice class that is managed by spring
-
<aop:aspect ref= "Logger" >


<!--define the type of notification
Aop:before defining a pre-notification
Method: Methods name defined in the Slice class
Pointcut-ref: pointcut expression is a reference
-
<aop:before method= "Before" pointcut-ref= "PT"/>

This is the configuration inside the XML

Annotations with XML use code and explain
<!--open support for spring IOC--
<context:component-scan base-package= "Cn.itcast" ></context:component-scan>

<!--enable support for AOP annotations--
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>


/*
* Slice class:
* The enhancements to the log portion of the target object are implemented by methods in this class
* On the Slice class
* Define Slice Class
* On the Tangent method
* Use annotations to define notification types
*/
@Component ("Logger")
@Aspect
public class Logger {//This is configured on the class

/**
* Extract Pointcut expression
* @Pointcut: Define pointcut expressions
* This annotation needs to be configured on the method, this method is an empty method
* When applying this pointcut expression, you just need to introduce the method name.
* But requires method name () parentheses required
*/
@Pointcut (value= "Execution (* Cn.itcast.service.impl). *.*(..))") Note: It is also possible to change the two points in front of the class name to a point.
@Pointcut (value= "Execution (* cn.itcast.service.impl.*.add* (..))") This is to specify that the method is enhanced
public void Pt () {//define a generic, such as a pre-notification, post-notification and so on, just need to refer to this method name.

}

/**
* Define the pre-notification
* @Before:
* Value: Can be a pointcut expression or a reference to a pointcut expression
* Pointcut Expression
*/
@Before ("PT ()")
public void before () {
SYSTEM.OUT.PRINTLN ("Print log before entering method");
}


* This is a way to annotate the configuration XML

How to configure pure annotations


/*
* Slice class:
* The enhancements to the log portion of the target object are implemented by methods in this class
* On the Slice class
* Define Slice Class
* On the Tangent method
* Use annotations to define notification types
*/
@Component ("Logger")
@Aspect
public class Logger {

/**
* Extract Pointcut expression
* @Pointcut: Define pointcut expressions
* This annotation needs to be configured on the method, this method is an empty method
* When applying this pointcut expression, you just need to introduce the method name.
* But requires method name () parentheses required
*/
@Pointcut (value= "Execution (* Cn.itcast.service.impl). *.*(..))")
public void Pt () {

}

/**
* Define the pre-notification
* @Before:
* Value: Can be a pointcut expression or a reference to a pointcut expression
* Pointcut Expression
*/
@Before ("PT ()")
public void before () {
SYSTEM.OUT.PRINTLN ("Print log before entering method");
}


@AfterReturning ("PT ()")
public void afterreturning () {
System.out.println ("Print the log after executing the target method to get the return value");
}

@AfterThrowing ("PT ()")
public void afterthrowing () {
System.out.println ("Throw exception print log");
}

@After ("PT ()")
public void after () {
SYSTEM.OUT.PRINTLN ("Print logs in the final code block");
}

5. Defining Surround Notifications
/**
* Surround notification is a spring-provided
* A means for the programmer to manually specify the enhancement method to be performed,
* In this method you can customize the above 4 notification types as required
* In surround notification, you need to call the enhanced method manually
* With one object provided by spring Proceedingjoinpoint
* There is a method in this object that can call the enhanced method
* Pjp.proceed (); Implement the Enhanced method
* Eg: in the dynamic agent, Method.invoke ();
*
* @throws Throwable
*/
@Around ("Execution (* Cn.itcast.service.impl). *.*(..))")
Public Object Around (Proceedingjoinpoint pjp) throws Throwable {
System.out.println ("Pre-notification");
Object obj = null;
try{
obj = Pjp.proceed ();
System.out.println ("Post-notification");
}catch (Exception e) {
SYSTEM.OUT.PRINTLN ("exception notification");
E.printstacktrace ();
}finally{
System.out.println ("Final Notice");
}
return obj;
}
}







Configuration classes for/spring
Replace the remaining configuration items in the XML configuration file in the configuration class

/**
* 1. Declaring a configuration class
* 2. Open support for IOC
* 3. Turn on support for AOP annotations
* @EnableAspectJAutoProxy
*
*/
@Configuration
@ComponentScan (basepackages= "Cn.itcast")
@EnableAspectJAutoProxy
public class Config {

}





public class Client {

public static void Main (string[] args) {
Test the configuration of the IOC
ApplicationContext ac = new Classpathxmlapplicationcontext ("Bean.xml");
ApplicationContext ac = new Annotationconfigapplicationcontext (config.class);

CustomerService customerservice = (customerservice) ac.getbean ("CustomerService");
Customerservice.updatecustomer ();
}
}
It's a purely annotated way.

Examples of AOP things

@Component ("Logger")
@Aspect
public class Logger {

@Pointcut (value= "Execution (* Cn.crm.service.impl). *.*(..))")
public void Pt () {

}

@Around (value= "pt ()")
Public Object TX (Proceedingjoinpoint pjp) throws throwable{
Session session = NULL;
Transaction tx = NULL;

Object obj = null;

try {
Session = Hibernateutils.getcurrentsession ();
tx = Session.begintransaction ();

obj = Pjp.proceed ();

Tx.commit ();

} catch (Exception e) {
System.out.println ("abnormal appearance");
Tx.rollback ();

}finally {

System.out.println ("Final Code of Execution");

}

return obj;

}


}


public class client{
public static void Main (string[] args) {

ApplicationContext ac = new Classpathxmlapplicationcontext ("Bean.xml");

CustomerService customerservice = (customerservice) ac.getbean ("CustomerService");


Customer customer = new Customer ();

Customer.setcustname ("Hello");

Customerservice.addcustomer (customer);
}

}

XML configuration:
<context:component-scan base-package= "Cn.crm" ></context:component-scan>

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>



This is a small case of AOP things,of course, spring also provides the support of things, but today only to do an AOP thing, hope to help everyone

The use of XML and annotations for 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.