Simple Application of SpringAOP in projects

Source: Internet
Author: User

Zookeeper


Simple Application of SpringAOP in projects

I. Preface project background as the company's data center expires, application migration (including databases) needs to be performed and cut off to the cloud platform. However, one-time cutover is not supported. three stages are required: the first stage is used to cut two cities, the second stage is used to cut nine cities, and the third stage is used to cut the whole area. In the first and second phases, you must ensure that the applications on the cloud platform and the current network platform can run in parallel. Therefore, to ensure normal data access on both sides, some functions need to be modified. For example, if a sub-function is not cutover in the parallel stage, you need to access the databases on both sides for verification during user login verification.
Technical Background this transformation involves application transformation. It is necessary to modify the original code to ensure normal functionality in the parallel stage. In this case, we need to maintain two sets of code: one set of cloud platform and one set of current network. In addition, at the end of cutover, you also need to restore the code, the workload is very large, and the risk is high. Later I thought that SpringAOP could be used to add some additional processing without modifying the original code. In addition, as long as the configuration is complete, the function also supports hot plugging (remove the configuration ).
Ii. SpringAOP I have found a lot of relevant information about springAOP on the Internet. Here I will make an integration and summary. Of course, I just have a preliminary understanding and have not studied its code implementation in depth.

AOP Concept

Aspect-Oriented Programming (also called Aspect-Oriented Programming): Aspect Oriented Programming (AOP) is a hot spot in software development and an important part of Spring framework. AOP can be used to isolate all parts of the business logic, thus reducing the Coupling Degree between each part of the business logic, improving the reusability of the program, and improving the development efficiency.

AOP is a continuation of OOP.

Its main functions include logging, Performance Statistics, security control, transaction processing, and exception handling.

The main intention is to divide the log records, Performance Statistics, security control, transaction processing, Exception Processing and other codes from the business logic code. By separating these behaviors, we hope that they can be independent into non-guided business logic methods, and thus change these behaviors without affecting the business logic code.

The pre-compilation method and runtime dynamic proxy can be used to dynamically and uniformly add functions to the program without modifying the source code. AOP is actually a continuation of the GoF design model. The design model tirelessly pursues decoupling between callers and callers to improve code flexibility and scalability. AOP can be said to be an implementation of this goal.

Spring provides rich support for Aspect-Oriented Programming, allowing cohesion development by separating application business logic and system-level services (such as audit and transaction management. Application objects only implement what they should do -- complete the business logic -- that's all. They are not responsible (or even conscious) for other system-level concerns, such as log or transaction support. Introduction to AspectJ

AspectJ is a long-standing Implementation of AOP, which can be used with Java.

Here we will introduce several concepts that must be understood in AspectJ:

· Aspect: the official abstraction is defined as "modularity of a focus, which may cross multiple objects". In this example, the "aspect" refers to the specific behavior followed by TestAspect, for example, AServiceImpl. the call of lift () is one of the actions that concern TestAspect. "Aspect" is configured in ApplicationContext.

· Joinpoint: a line in the program execution process is, for example, an AServiceImpl. Invoke () call or BServiceImpl. barB (String_msg, int _ type) throw an exception.

· Advice: the action taken by the "cut-plane" for a "connection point", for example, com. spring. an Advice is used to record all the class methods in the service package. One slice can contain multiple "Advice", such as TestAspect.

· Pointcut: an assertion that matches the connection point. In AOP, it is notified to associate with a Pointcut expression. For example, the connection points of all notifications in TestAspect are determined by the entry point expression execution (* com. spring. service. *. * (...).

· Target Object: The Object notified by one or more slices. For example, AServcieImpl and BServiceImpl, of course, Spring AOP adopts proxy implementation during actual running, and actual AOP operates on the proxy object of TargetObject.

· AOP Proxy has two Proxy methods in Spring AOP: JDK dynamic Proxy and CGLIB Proxy. By default, when TargetObject implements an interface, JDK dynamic proxy is used, for example, AServiceImpl; otherwise, CGLIB proxy is used, for example, BServiceImpl. To use the CGLIB proxy forcibly, set the proxy-target-class attribute to true.

We are using this framework for business rectification. The main logic code is the notification (Advice), which is commonly used in the following types:

· Before advice: A notification executed Before a connection point. However, this notification cannot be executed Before a connection point. Use the element in ApplicationContext for declaration. For example, the doBefore method in TestAspect

· Post notification (After advice): The Notification executed when a connection point exits (whether it is a normal return or an abnormal exit ). Use the element in ApplicationContext for declaration. For example, the doAfter method in TestAspect, so when BServiceImpl. barB is called in AOPTest to throw an exception, the doAfter method is still executed

· After return notification (After return advice): The Notification executed After a connection point is normal, excluding the exception thrown. Use the element in ApplicationContext for declaration.

· Around advice: notifications that enclose a connection point, similar to the doFilter method of the Filter in the Servlet specification in the Web. You can customize the behavior before and after the method is called, or you can choose not to execute. Use the element in ApplicationContext for declaration. For example, the doAround method in TestAspect.

After throwing advice: the notification that is executed when the method throws an exception and exits. Use the element in ApplicationContext for declaration. For example, the doThrowing method in TestAspect.

II. Introduction to Spring AOP

In addition to the core package of spring, several packages of aspectjrt. jar, aspectjweaver. ja and cglib-nodep.jar are also required.

Import an aop. xml configuration in ApplicationContext. xml, as shown below:

 
 
  
   
Aop Configuration
  
        
 

Note: here we mainly implement AOP Based on the annotation method. For specific implementation classes, see the following content. This prevents throwing java. lang. IllegalArgumentException exceptions because the dynamic proxy used by AOP can be used for interfaces or classes. Java Dynamic proxy can only be used for interfaces. When Spring AOP is used, the default dynamic proxy is for the interface, but we are for the class, so we need to add proxy-target-class = "true ".

Configure multiple data sources

Because of project requirements, dynamic data sources need to be configured, and applications on the current network may need to access the Apsara stack database.

The Dao. xml configuration is as follows (the c3p0 database connection pool is used here, And springJDBC is used for database operations ):

 
 
  
          
           
           
           
           
           
           
           
   
  
  
          
           
           
           
           
           
           
           
   
  
  
  
   
   
    
     
     
   
   
  
  
      
      
  
   
  
  
   
  
  
   
  
  
   
  
 

The dynamic database class structure is as follows (the implementation on the Internet is used for reference here ):
DataSorceEntry. Is the interface:
Public interface performanceentry {// cloud platform Data Source flag public final static String YUN_SOURCE = "performance2"; // public final static String CURR_SOURCE = "dataSource "; /***** restore the data source **/public void restore ();/***** switch the data source */public void switchSource (); /*** set the data source ** @ param dataSource */public void set (String source);/*** get the data source ** @ return String */public String get (); /*** clear the data source */public void clear ();}

Performanceentryimpl is the implementation class of DataSorceEntry:
Public class performanceentryimpl implements performanceentry {private final static ThreadLocal
 
  
Local = new ThreadLocal
  
   
(); Public void clear () {local. remove ();} public String get () {return local. get ();} public void restore () {local. set (null); // set null data source} public void set (String source) {local. set (source);} public void switchSource () {if (performanceentry. CURR_SOURCE.equals (get () {set (performanceentry. YUN_SOURCE);} else {set (performanceentry. CURR_SOURCE );}}}
  
 

DynamicDataSource inherits the AbstractRoutingDataSource (springjdbc multi-data source routing class) class, which uses the DataSorceEntry instance as the data source selection class and is implemented in the injection mode:
public class DynamicDataSource extends AbstractRoutingDataSource {@Autowiredprivate DataSourceEntry dataSourceEntry;@Overrideprotected Object determineCurrentLookupKey() {return this.dataSourceEntry.get();}@Resourcepublic void setDataSourceEntry(DataSourceEntry dataSourceEntry) {this.dataSourceEntry = dataSourceEntry;}}
Rebuild instance

Here, we will describe one of the transformation implementations. to simplify it, we will introduce the login verification function of a subsystem, because this subsystem does not cutover during the parallel process, therefore, user authentication requires access to the databases on both platforms.

DaYiAspest. java:

@ Component @ Aspectpublic class DaYiAspest {@ Autowiredprivate performanceentry; // Dynamic Data Source // configure the ing point set @ Pointcut ("execution (* cn. qtone. xxt. parentnew. kwfd. controller. *. dayi (..)) "+" | execution (* cn. qtone. xxt. schoolnew. kjck. controller. *. dayi (..)) "+" | execution (* cn. qtone. xxt. studentnew. kwfd. controller. *. dayi (..)) ") public void pointcuts () {}/ *** single-point Logon (switch-in to replace the original method) ** @ param request * @ param response * @ return * @ throws IOException */@ Around (value = "pointcuts ()") public Object dayiLoginInit (ProceedingJoinPoint pjp) throws IOException {HttpServletRequest request = (HttpServletRequest) pjp. getArgs () [0]; HttpServletResponse response = (HttpServletResponse) pjp. getArgs () [1]; Object obj = null; // The operation obj = pjp before the method is executed. proceed (); // perform the original operation // return obj after the original method is executed ;}}

Note: @ Pointcut can define multiple entry point sets, or directly @ Around ("execution expression"). Here we will introduce the execution expression:

Spring AOP users may often use execution pointcut designator. The execution expression format is as follows:

Execution (modifiers-pattern? Ret-type-pattern declaring-type-pattern? Name-pattern (param-pattern) throws-pattern ?) Except for the return type mode (ret-type-pattern in the code snippet above), the name mode and parameter mode are all optional. The return type mode determines that the return type of the method must match a connection point in sequence. The most frequent return type pattern you will use is *, which indicates matching any return type. Only the methods of the given type are returned. The name pattern matches the method name. You can use the * wildcard as the all or part of the naming mode. The parameter mode is a little complicated: () matches a method that does not accept any parameters, and (...) matches a method that accepts any number of parameters (zero or more ). The mode (*) matches a method that accepts any type of parameters. The mode (*, String) matches a method that accepts two parameters. The first method can be of any type, and the second method must be of the String type. See the Language Semantics section in the AspectJ programming guide.

Below are some examples of common entry point expressions.

Execution of any public method:

Execution (public ** (...) any execution of a method starting with "set:

Execution (* set * (..) execute any method of the AccountService interface:

Execution (* com. xyz. service. AccountService. * (..) defines the execution of any method in the service package:

Execution (* com. xyz. service. *. * (..) defines the execution of any method in the service package or sub-package:

Execution (* com. xyz. service... *. * (...) any connection point in the service package (in Spring AOP, only method execution is performed ):

Within (com. xyz. service. *) Any connection points in the service package or sub-package (in Spring AOP, only method execution is performed ):

Within (com. xyz. service... *) implements any connection point of the proxy object of the AccountService interface (in Spring AOP, only method execution is performed ):

This (com. xyz. service. accountService) 'this' is used in binding form for more information:-see the following section on How to Make proxy objects accessible in the notification body.

Any connection point of the target object implementing the AccountService interface (in Spring AOP, only method execution is performed ):

Target (com. xyz. service. accountService) 'target' is used in binding form:-the following section describes how to make the target object accessible in the notification body.

Each parameter that accepts only one parameter implements the connection point of the Serializable interface (in Spring AOP, only method execution is performed)

Args (java. io. serializable) 'args 'is used in binding form. For more information about how to make method parameters accessible in the notification body, see the following section.

Note that the starting point in the example is different from execution (** (java. io. serializable): args matches only Serializable parameters passed in during dynamic running, while execution matches the Serializable interface when the type of the signature Declaration of the input parameter is implemented.

There is an arbitrary connection point in the target object of @ Transactional annotation (in Spring AOP, only method execution is performed)

@ Target (org. springframework. transaction. annotation. transactional) '@ target' can also be used in binding form: See the following section of the notification to discuss how to make the annotation object accessible in the notification body.

The Declaration type of any target object has a connection point with @ Transactional annotation (in Spring AOP, only method execution is performed)

@ Within (org. springframework. transaction. annotation. transactional) '@ within' can also be used in bindingform:-see the section on how to make the annotation object accessible in the notification body in the following sections of the notification section.

Any method executed has a @ Transactional annotation connection point (in Spring AOP, only method execution is performed)

@ Annotation (org. springframework. transaction. annotation. transactional) '@ annotation' can also be used in binding form:-see the section on how to make the annotation object accessible in the notification body in the following sections.

Any input parameter that accepts one parameter implements the @ Classified annotation connection point at runtime (in Spring AOP, only method execution is performed)

@ Args (com. xyz. security. classified) '@ args' can also be used in bindingform:-see the section on how to enable an annotation object to be accessed in the notification body in the following section.

In addition, I mainly use the @ Around annotation here. In fact, there are several other methods, and their functions are different:

@ Before: pre-notification. The pre-notification is executed Before the set of cut points;

@ After: Post-notification. After the set of cut-point methods is executed, the post-notification is executed;

@ AfterReturning: Post-notification. After the cut-point method set is executed and the result is returned, the post-notification is executed;

@ Around: surround notification (# The ProceedingJoinPoint parameter must be included in the surround notification method, which is similar to the doFilter method in the Filter)

@ AfterThrowing;

Specific instance can see: http://blog.sina.com.cn/s/blog_7ffb8dd501014am6.html

Here is a problem: because the original method is: public ModelAndView dayiLoginInit (HttpServletRequest request) has only one parameter, so the preceding statement:
HttpServletResponse response = (HttpServletResponse) pjp.getArgs()[1];
The exception of data out-of-bounds is reported, because some modulo uses the response parameter. To solve this problem, I found a solution on the Internet, that is, configuring the filter, and the thread variable ThreadLocal is used to implement: filter:
Import java. io. IOException; import javax. servlet. filter; import javax. servlet. filterChain; import javax. servlet. filterConfig; import javax. servlet. servletException; import javax. servlet. servletRequest; import javax. servlet. servletResponse; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/*** @ Description: cloud Platform cutover Filter * @ author ke yingbo * @ date 2014-4-1 03:04:34 * @ version v1.0 */public class GetContextFilter implements Filter {@ Overridepublic void destroy () {}@ Overridepublic void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {SysContext. setRequest (HttpServletRequest) request); SysContext. setResponse (HttpServletResponse) response); chain. doFilter (request, response) ;}@ Overridepublic void init (FilterConfig filterConfig) throws ServletException {// TODO Auto-generated method stub }}

SysContext storage variables:

Package cn. qtone. xxt. base. aop; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/*** @ Description: system request context (mainly used to store request and response objects) * @ author ke yingbo * @ date 2014-4-1 02:49:58 * @ version v1.0 */public class SysContext {private static ThreadLocal
 
  
RequestLocal = new ThreadLocal
  
   
(); Private static ThreadLocal
   
    
ResponseLocal = new ThreadLocal
    
     
();/*** @ Description: Get the HttpServletRequest object * @ return setting file */public static HttpServletRequest getRequest () {return (HttpServletRequest) requestLocal. get ();}/*** @ Description: sets the HttpServletRequest object * @ return setting file */public static void setRequest (HttpServletRequest request) {requestLocal. set (request);}/*** @ Description: Get the HttpServletResponse object * @ return setting file */public static HttpServletResponse getResponse () {return (HttpServletResponse) responseLocal. get ();}/*** @ Description: sets the HttpServletResponse object * @ return setting file */public static void setResponse (HttpServletResponse response) {responseLocal. set (response);}/*** @ Description: clear configuration variables */public static void clear () {requestLocal. remove (); responseLocal. remove ();}}
    
   
  
 
Then, as long as the filter is configured, the above request and response object can be obtained as follows:

HttpServletResponse response = SysContext.getResponse();HttpServletRequest request =  SysContext.getRequest();

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.