General configuration and deployment tutorials for AOP projects in the Java Spring Framework _java

Source: Internet
Author: User
Tags aop exception handling object model java spring framework

0. With regard to AOP
facet programming (also called aspect-oriented programming): Aspect Oriented Programming (AOP) is a hotspot in software development and an important part of the spring framework. The use of AOP can isolate the parts of the business logic, so that the coupling between the parts of the business logic is reduced, the reusability of the program is improved, and the efficiency of the development is improved.

AOP is the continuation of OOP.

The main functions are: Logging, performance statistics, security control, transaction processing, exception handling and so on.

The main intent is to log records, performance statistics, security controls, transaction processing, exception handling, and so on, are separated from the business logic code, and by separating them we want to be able to separate them into methods that do not guide the business logic, and then change the behavior without affecting the code of the business logic.

A technique for dynamically adding functionality to a program without modifying the source code can be achieved through precompilation and runtime dynamic proxies. AOP is actually a continuation of the GOF design pattern, the design pattern pursues the decoupling between the caller and the callee, improves the flexibility and scalability of the code, and AOP can be said to be an implementation of this goal.

Provides rich support for aspect-oriented programming in spring, allowing for cohesive development through separation of application business logic and system-level services such as audit (auditing) and transaction (transaction) management. Application objects only implement what they should do--complete the business logic--that's all. They are not responsible (or even conscious) of other system-level concerns, such as logs or transactional support.

1. Load additional external configuration files or property files in spring by Propertyplaceholderconfigurer:
in many Java EE projects, the role of spring is very important, a lightweight container for managing other modules and components, and spring often needs to manage struts, Ibatis, hibernate, etc. These open source framework profiles are managed through spring's propertyplaceholderconfigurer load in spring, and database connection information, The Jndi connection information properties file can also be managed by propertyplaceholderconfigurer loading into spring. Usage is as follows:
(1). Load additional files into spring by Propertyplaceholderconfigurer:
Add the following configuration in the spring configuration file:

<bean class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > 
    <property Name= "Locations" > 
       <value>classpath: filename to load </value> 
       ... 
    </property> 
</bean> 


(2). The configuration or property file that is to be loaded after the configuration in (1) is loaded into spring. If you also need to use some of the information that is loaded in the configuration or data file at run time, such as using database connection information or Jndi connection information, you can use the syntax of the type El expression to refer to the For example:

<bean id= "DataSource" destroy-method= "Close" class= "Org.apache.common.dbcp.BasicDataSource" > 
    <!-- Suppose that the database connection information is written in the external properties file and is already loaded by spring--> 
    <property name= "Driverclassname" value= "${driver}"/> 
    < Property name= "url" value= "${url}"/> 
    <property name= "username" value= "${username}"/> 
    Name= "Password" value= "${password}"/> 
</bean> 


Note: You can also use <context:property-placeholderlocation= "classpath: filename to load"/>

2. Dynamic Proxy for Java:
the underlying implementation of spring's aspect-oriented programming (AOP) is dynamic proxies, so you must understand dynamic proxies before you can learn the aspect-oriented programming.
Dynamic proxy is widely used in Java, and dynamic Proxy is one of the most popular classical design patterns in the 23 design pattern. The principle of dynamic proxy is that when a target object or its method is invoked, the system does not return the target object directly, but instead returns a proxy object that accesses the target object or target object through the proxy object.
The simple principle of dynamic proxy is as follows:
The client caller--> the proxy object--> the target object being invoked.
When a client invokes a proxy object, the proxy object delegates the target object to its business method.
Dynamic agent is divided into two kinds, for the dynamic agent of the interface and dynamic proxy for the ordinary class, the dynamic Proxy in Java is the dynamic proxy of the real interface, Cglib is the dynamic agent for the ordinary class, the target Java EE's dependency package and Spring's jar package already contains the Cglib related jar package, Therefore, the agent can also be a dynamic proxy for the normal class.
(1). Java's dynamic proxy for interfaces:
Dynamic proxies in Java can only be dynamic proxies for interfaces, so the target object must implement an interface, and the proxy object implements all the interfaces of the target object. The work flow is as follows:

A. Dynamic proxy class authoring:
Note: The dynamic proxy must implement the Invocationhandler interface while implementing the following methods:

Copy Code code as follows:

Object Invoke (Objectm proxy instance, method instance of the interface methods invoked on the proxy instance, object[] An array of objects of the parameter values of the method call on the incoming proxy instance);

A documentation description of the installation JDK that is used to pass the proxy instance, identify the Java.lang.reflect.Method object that calls the method, and an array of type object that contains the parameters. The calling handler handles the encoded method call in the appropriate way, and the result it returns is returned as the result of a method call on the proxy instance.

B. Create a proxy object:

Proxy.newproxyinstance (class loader, class<?>[] interface array, callback proxy object (typically this)) 


When the target object method is invoked, this method creates a proxy object for the target object, and the proxy object automatically invokes its Invoke method to call the target object and returns the result of the call.

(2). Cglib for ordinary Java class dynamic proxy:
Cglib when creating a dynamic proxy, the target class is not required to implement an interface, and the workflow is as follows:
A. Dynamic proxy class authoring:

Enhancer enhancer = new enhancer (); 
Sets the parent class of the target class to its own 
Enhancer.setsuperclass (Target class object. GetClass ()); 
Sets the callback object as the dynamic proxy object itself 
enhancer.setcallback (this); 


B. Implementing the Methodinterceptor interface:
Implement the following methods:

Object Intercept (OBJECTM proxy instance, method instance of interface methods invoked on proxy instance, object[] array of parameter values of method calls on the incoming proxy instance, Methodproxy method proxy instance);

Note: Cglib can be used not only for class dynamic proxies, but also for method dynamic proxies.

3. Basic concepts for cutting-plane programming (AOP):
take an example of a common Java method

Public return type method name (parameter list) {--> wrapping notification 
    method before processing code  -->   Notification 
try{ 
    method Concrete Implementation (method body) ... 
    method post-processing code-  - >   Post Notification 
}catch (exception type E) { 
    exception handling    ... -->   Exception notifies 
}finally{ 
    last processing agent    ... -->   final notification 
} 
} 


A. crosscutting concerns: In Java objects, such as the location of the 5 notifications above, objects that have similar processing logic, such as permission validation, object processing, logging, etc., are referred to as crosscutting concerns, object-oriented programming (OOP) Focus is the vertical abstraction of real-world things into programming object models. The focus of aspect-oriented programming (AOP) is horizontal, which abstracts the parts of the programming object model with similar processing logic to form facets, while the processing logic in programming objects is crosscutting concerns.
B. Cut (Aspect): The crosscutting concerns are abstracted to form a slice, similar to a class, with different concerns, classes are abstractions of the attributes of things, and cuts are abstractions of crosscutting concerns.
C. Connection point (Joinpoint): The point that is intercepted, the method in spring, because spring only supports the connection point of the method type, that is, the method being intercepted. As in the above example method.
D. Pointcut (Pointcut): the definition of the connection point to intercept, is a collection of connection points, that is, a series of blocked methods of the collection.
E. Notice (Advice): Refers to what to do after intercepting to the connection point, that is, the logical processing after interception. The usual permissions validation, things processing, logging and other operations are defined and completed in the notification.
F. Target object: Target object of the proxy, that is, the object being intercepted. As in the example above, the object of the method.
G. Weaving (Weave): The process of applying a slice to a target object and causing the proxy object to be created.
H. Introduction (Introduction): Without modifying the code, introduce methods and fields that can be dynamically added to the class at run time.

4. Spring supports dependency packs for aspect-oriented programming (AOP):
Spring Extracts the following 3 packages in the directory:

Lib/aspectj/aspectjweaver.jar
Lib/aspectj/aspectjrt.jar
Lib/cglib/cglib-nodep-2.1-3.jar

5. When using aspect-oriented programming (AOP) in spring, you need to introduce an AOP namespace into the spring configuration file, which adds the following configuration:

xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" 
"HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP 
http ://www.springframework.org/schema/aop/spring-aop-2.5.xsd " 


Note: Spring2.5 provides two AOP methods, based on the XML configuration file approach and Java annotations.
To use AOP in annotation mode, you need to add the following object annotation methods to the spring configuration file AOP support:

<aop:aspectj-autoProxy/> 


6. JavaBean Packaging class--beanwrapper:
Spring encapsulates a javabean behavior through the Beanwrapper class, and can set and get its property values, such as:

Beanwrapper Packaging Class object = Beanwrapperimpl (New wrapped Class ()); 
Wrapper class object. setPropertyValue ("Property name", "property value"); 


In this way, you can set properties for the wrapped class.

7. Annotation-oriented facet programming (AOP) Development:
(1). Include AOP support for the annotation method in the spring configuration file.
(2). Define the Slice:
Similar to creating a generic class, add a "@Aspect" annotation before the class to indicate that the class is a slice.
(3). Add a pointcut to the slice:
A pointcut is a collection of object methods that are blocked, and usually the Pointcut defines a method that handles the pointcut in the slice. Using the @Pointcut annotation, the syntax is as follows:

@Pointcut ("Execution" (* com.test.service. *.* (..)) ") 
The public void Anymethod () {//Method name is pointcut name 
pointcut processing 
} 


Syntax parameter detailed:
A. The first "*": Indicates that the method being intercepted is any return type.
B. Com.test.service: Here is a simple example of the name of the package to be intercepted, that is, the packet being intercepted.
C. Two ".." After the intercepted package name. : Indicates that the packets under the intercepted packet are also recursively intercepted, that is, the intercepted child packets.
D. ".." After "*": represents all classes under the blocked package and its child packages, that is, blocked classes.
E. Last "*": represents all methods in the blocked class, that is, the method being intercepted.
F. "(..)" : means that the intercepted method receives arbitrary parameters, that is, the intercepted parameter.
Note: The pointcut definition syntax can support wildcard characters, but you must strictly follow the syntax rules. Such as:

@Pointcut ("Execution" (*com.test.service. *.add* (..)) ")

Represents an interception of a method that starts with "add" in all classes under the Com.test.service package and its child packages.
(4). Add a notice to the slice:
Refer to the small example in 3 for the notification location in spring.
@Before annotation: Declaring a predecessor notification.
@AfterRutruning NOTE: Declare a post notification.
"@After" NOTE: Declare final notice.
@AfterThrowing annotation: Declares an exception notification.
@Around Note: Declares a surround notification.
An example of a definition notification is as follows:

@Before ("Anymethod () (Pointcut name declared in section)") Public 
void Doaccesscheck () { 
    ... 
} 


Note: There is a slight difference between surround notification and 4 other notifications, wrapping notifications are defined in a special way, wrapping notifications work before and after the entire method call, so you must use a connection point object to tell the connection point to continue its logical processing after wrapping the notification processing. This is defined in the following way:

@Around (pointcut name) public 
Object dobasicprofiling (Procedingjoinpoint pjp) throws throwable{... 
    return Pjp.proceed ()//The sentence is to tell the connection point to continue to perform other actions 
} 

8. Some tips for developing facet-oriented programming (AOP) based on annotations:
(1). Get input parameters:
Such as:

@Before (pointcut name && args (input parameter name)) public 
void dosomething (String input parameter name) {...} 


(2). Get return Result:
Such as:

@AfterReturning (pointcut= "pointcut name", returning= "return result name") Public 
void dosomething (String result name) {...} 


9. An xml-based approach to slicing programming (AOP) Development:
(1). Define the Slice class and add the notification in the slice class.
(2). The slice class is configured in the spring configuration file like a normal Java class.
(3). Add an AOP configuration to the spring configuration file as follows:

<aop:config> 
    <!--configuration slice--> 
    <aop:aspect id= "Slice id" ref= "the ID of the slice class in the spring configuration file" > 
       <!-- Configuration pointcut--> 
       <aop:pointcut id= "pointcut id" 
expression= Execution (* com.test.service. *.*(..))” /> 
       <!--configuration notification--> 
       <aop:before pointcut-ref= "pointcut id" method= "the corresponding processing method in the slice class" 
       /> <AOP: After ....../> ... 
</aop:aspect> 
</aop:config> 


transaction processing of Spring (declarative transaction processing in spring):
transaction simply refers to one of the most basic operations in the database, and the detailed explanation of the transaction will be specified in the database related summary later. One of the most important applications of spring's aspect-oriented programming (AOP) is transaction management, where the Spring2.5 version of transaction management supports both annotations based and xml-based methods:
(1). Transaction management based on annotation mode:
A. Add the namespace of the transaction management in the spring configuration file as follows:

Xmlns:ts=http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx 
http:// Www.springframework.org/schema/tx/spring-tx-2.5.xsd 


B. Configure the transaction manager in the spring configuration file as follows:

<bean id= "Txmanager" class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" > 
    < ID of the data source bean configured in the property name= "DataSource" ref= "Spring"/> 
</bean> 

C. Add a transaction configuration entry that supports annotations in the spring configuration file as follows:

<tx:annotation-driventransaction-managertx:annotation-driventransaction-manager= "TxManager ( The ID of the transaction manager Bean configured in spring "/> 

D. Using annotation-based transaction management:
In the Java EE Project managed by spring, you need to use the business logic place of the transaction plus the "@Transactional" annotation.

(2). Transaction management based on XML file mode:
A. Configure the transaction manager in the spring configuration file as follows:

<bean id= "Txmanager" class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" > 
    < ID of the data source bean configured in the property name= "DataSource" ref= "Spring"/> 
</bean> 

B. Add the aspect of things management in the spring configuration file as follows:

<aop:config> 
    <!--configure transaction pointcuts--> 
    <aop:pointcut id= "transactionpointcut" 
expression= " Execution (* com.test.service. *.*(..))” /> 
<!--Configure transaction notifications-->   
<aop:advisor advice-ref= "Txadvice" pointcut-ref= "Transactionpointcut"/> 
</aop:config> 
 
C. Add an object handling attribute to a transaction notification in the spring configuration file as follows:
 
<tx:advice id= "Txadvice" transactionmanager= "Txmanager" > 
    <tx:attributes> 
       <!-- This example sets the Query method beginning with get to read-only and does not support transaction--> 
       <tx:method name= "get*" read-only= "true" propagation= "not_supported"/ > 
       <!--Other methods set to spring default behavior--> 
       <tx:method name= "*"/> 
    </tx:attributes> 

Related Article

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.