Spring AOP Details and Spring Configuring AOP with XML

I. overview


  • Aspect Oriented Programming: Aspect Oriented Programming
  • AOP is to extract the duplicate code of our program. When it needs to be executed, we use dynamic proxy technology to enhance our existing methods without modifying the source code.
  • AOP: Aspect-oriented programming, AOP is to mark a class or method before and after execution, declare what to execute before execution here, what to execute after execution here, insert a new execution method. In Spring, it is based on the dynamic proxy technology of JVM, and then designs a series of AOP transverse implementations, such as pre-notification, return notification, exception notification, etc. At the same time, Pointcut interface matches the entry point. It can use the existing entry point to design the cross-cutting aspect, and it can also expand the relevant methods to cut in according to the requirements.

2. Role:

  • During the running of the program, the existing methods are enhanced without modifying the source code.

3. Advantages:

  • Reduce duplication of code
  • Improving Development Efficiency
  • Convenient maintenance

4. Implementation of AOP

  • Using Dynamic Agent Technology
    About Dynamic Agent click

2. AOP (Face-Oriented Programming)

1. Terminology related to AOP

  • Joinpoint: Points that are intercepted. In spring, these points refer to methods, because spring only supports join points of method types.
  • Pointcut: The definition of which Joinpoint s we want to intercept.
  • Advice: Notification is what you do when you intercept a Joinpoint.
    Types of notifications: pre-notification, post-notification, exception notification, final notification, surround notification.
  • Introduction: A special notification that dynamically adds methods or fields to a class at runtime without modifying the class code.
  • Target: The target object of the agent.
  • Weaving: The process of applying enhancements to target objects to create new proxy objects.
    spring uses dynamic proxy weaving, while AspectJ uses compile-time weaving and class-loading weaving.
  • Proxy (proxy): When a class is enhanced by AOP weaving, a result proxy class is generated.
  • Aspect: A combination of entry points and notifications.

2. What AOP in spring Should Be Clear

a. Development phase (programmers do)

  • Writing core business code (development mainline): Most programmers do it, requiring familiarity with business requirements.
  • Extract the common code and make the notification. (Do it at the end of the development phase): AOP programmers do it.
  • In the configuration file, declare the relationship between the entry point and the notification, that is, the aspect. AOP programmers do it.

b. Running phase (completed by Spring framework)

  • The Spring framework monitors the execution of pointcut methods. Once the entry point method is monitored, the agent mechanism is used to dynamically create the agent object of the target object. According to the notification category, the corresponding function of the notification is weaved into the corresponding location of the agent object, and the complete code logic operation is completed.

III. XML Configuration AOP Steps

Step 1: Configure the package to be searched

<context:component-scan base-package="cn.lemon"></context:component-scan>

Step 2: Declare AOP configuration using aop:config

  • Role: Configuration used to declare the start of aop
<! - AOP configuration
     # proxy-target-class="true": Using CGLib proxy, the default is interface proxy (JDK proxy)
<aop:config proxy-target-class="true">
        <! - The configuration code is written here - >.

Step 3: Configuring facets using aop:aspect

  • Function: Used to configure sections.
  • Attribute: id: Provides a unique identifier for the section. ref: Refers to the ID of the configured notification class bean.
<aop:aspect ref="loggerAdvice">
     <! - The type of configuration notification should be written here - >.

Step 4: Configure pointcut expressions using aop:pointcut

  • Role: Used to configure pointcut expressions. It specifies which classes and methods to enhance.
  • Property: expression: Used to define pointcut expressions. id: Used to provide a unique identifier for pointcut expressions
<! -- Point-of-entry expressions: Define those methods for weaving enhancements - >
< aop: pointcut id = "service method" expression = "execution (* cn. lemon. service. impl. *. * (.))"> < / aop: pointcut > <! - entry point - > <

Pointcut expression description
Expression grammar: execution([modifier] return value type package name, class name, method name (parameter))
Full matching mode:

public void cn.lemon.service.impl.AccountServiceImpl.addAccount(cn.lemon.domain.Account)

Access modifiers can be omitted

void cn.lemon.service.impl.AccountServiceImpl.addAccount(cn.lemon.domain.Account)

The return value can use the * sign to represent any return value.

* cn.lemon.service.impl.AccountServiceImpl.addAccount(cn.lemon.domain.Account)

Packet names can use * numbers to represent arbitrary packages, but there are several levels of packages that need to be written*

 * *.*.*.*.AccountServiceImpl.addAccount(cn.lemon.domain.Account)

Use... to represent the current package and its subpackages

 * cn..AccountServiceImpl.addAccount(cn.lemon.domain.Account)

Class names can use the * sign to represent any class

 * cn..*.addAccount(cn.lemon.domain.Account)

The method name can use a * sign to represent any method:

 * cn..*.*( cn.lemon.domain.Account)

The parameter list can use *, indicating that the parameter can be of any data type, but it must have parameters:

 * com..*.*(*)

The list of parameters can be used to indicate whether parameters are available or not, and parameters can be of any type:

 * com..*.*(..)

Full formula:

 * *..*.*(..)

Be careful:
Usually, we all enhance the business layer approach, so pointcut expressions are cut to the business layer implementation class.

execution(* com.lxs.service.impl.*.*(..))

Step 5: Configure the corresponding notification type using aop:xxx

<aop:before method="before" pointcut-ref="serviceMethod"></aop:before><!--Weaving pre-reinforcement-->
<aop:after-returning method="afterReturning" pointcut-ref="serviceMethod" returning="result"></aop:after-returning><!--Post enhancement-->
<aop:around method="around" pointcut-ref="serviceMethod"></aop:around><!--Surround enhancement-->
<aop:after-throwing method="exception" pointcut-ref="serviceMethod" <aop:after method="after" pointcut-ref="serviceMethod"></aop:after><!--Final enhancement-->

Fourth, Spring configures AOP using XML

1. New persistence layer (dao), interface and implementation class

package cn.lemon.dao;

public interface IAccountDao {
    void in(Double money);

    void out(Double money);
package cn.lemon.dao.impl;

import cn.lemon.dao.IAccountDao;
import org.springframework.stereotype.Repository;

public class AccountDaoImpl implements IAccountDao {
    public void in(Double money) {
        System.out.println("Successful transfer" + money + "Yuan Yuan");

    public void out(Double money) {
        System.out.println("Successful turn out" + money + "Yuan Yuan");

2. New Business Layer (service), Interface and Implementation Class

package cn.lemon.service;

public interface IAccountService {
    void transfer(Double money);
package cn.lemon.service.impl;

import cn.lemon.dao.IAccountDao;
import cn.lemon.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

public class AccountServcieImpl implements IAccountService {
    private IAccountDao iAccountDao;

    public void transfer(Double money) {

3. Enhancement class

package cn.lemon.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

public class LoggerAdvice {
     * @param joinPoint Getting information about business methods
     *                  getSignature() Signatures
    public void before(JoinPoint joinPoint){
        System.out.println("Open Transaction: Pre-Enhancement, Method Named:" + joinPoint.getSignature().getName());
    public void afterReturning(JoinPoint joinPoint,Object result){
        System.out.println("Submit transactions: Post-enhancements, called:" + joinPoint.getSignature().getName() + "The return value is:" + result);

    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("Enhancement around the front.......");
        //Implementing business methods
        Object result = proceedingJoinPoint.proceed();
        System.out.println("Enhancement around the rear...");
        return result;

    public void exception(JoinPoint joinPoint,Exception e){
        System.out.println("Abnormal enhancement, abnormal information is:" + e.getMessage());

    public void after(JoinPoint joinPoint){
        System.out.println("The final enhancement is called;" + joinPoint.getSignature().getName());

4. XML Configuration of AOP

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop
    <context:component-scan base-package="cn.lemon"></context:component-scan>

    <!--aop To configure
     # proxy-target-class="true": Using CGLib proxy, the default is interface proxy (JDK proxy)
    <aop:config proxy-target-class="true">
        <!--Pointcut expression:Define which methods weave enhancements-->
        <aop:pointcut id="serviceMethod" expression="execution(* cn.lemon.service.impl.*.*(..))"></aop:pointcut><!--breakthrough point-->
        <aop:aspect ref="loggerAdvice">
            <aop:before method="before" pointcut-ref="serviceMethod"></aop:before><!--Weaving pre-reinforcement-->
            <aop:after-returning method="afterReturning" pointcut-ref="serviceMethod" returning="result"></aop:after-returning><!--Post enhancement-->
            <aop:around method="around" pointcut-ref="serviceMethod"></aop:around><!--Surround enhancement-->
            <aop:after-throwing method="exception" pointcut-ref="serviceMethod" throwing="e"></aop:after-throwing><!--Abnormal enhancement-->
            <aop:after method="after" pointcut-ref="serviceMethod"></aop:after><!--Final enhancement-->

5. Test class

package cn.lemon.service.impl;

import cn.lemon.service.IAccountService;
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;

@ContextConfiguration(locations = "classpath:/applicationContext.xml")
public class AccountServcieImplTest {
    private IAccountService iAccountService;

    public void transfer() {

5. Spring uses annotations & XML to configure AOP

Tags: Spring xml Programming JDK

Posted on Wed, 11 Sep 2019 05:37:33 -0700 by ghadacr