XML Configuration for AOP

Basic usage steps

Imagine a scenario where there is a business layer for saving and updating accounts and deleting them, but what do I do when I print logs for saving, updating, and so on?

If we add code directly to the business tier, it's equivalent to adding code that doesn't matter.So here you can use Spring's AOP style to enhance in the original business-tier code.Business tier code AccountService.java And tangent classes Logger.java The code is as follows

IAccountService.java Interface

/**
 * Business Tier of Account
 */
public interface IAccountService {
    /**
     * Simulate Save Account
     */
    void saveAccount();

    /**
     * Update Account
     * @param i
     */
    void updateAccount(int i);

    /**
     * Delete Account
     */
    int deleteAccount();
}

AccountService.java

public class AccountServiceImpl implements IAccountService {
    @Override
    public void saveAccount() {
        System.out.println("Save performed");
    }

    @Override
    public void updateAccount(int i) {
        System.out.println("Update performed");
    }

    @Override
    public int deleteAccount() {
        System.out.println("Delete performed");
        return 0;
    }
}

Logger.java

public class Logger {

    /**
     * Before advice
     */
    public void beforePrintLog(){
        System.out.println("beforePrintLog Print logs...");
    }
    /**
     * after returning advise
     */
    public void afterPrintLog(){
        System.out.println("afterPrintLog Print logs...");
    }
    /**
     * Exception Notification
     */
    public void throwPrintLog(){
        System.out.println("throwPrintLog Print logs...");
    }
    /**
     * Return Notification
     */
    public void returnPrintLog(){
        System.out.println("returnPrintLog Print logs...");
    }
    /**
     * Around Advice
     */
    public Object aroundPrintLog(){
        .....
    }
    
}

Next, write in Spring's configuration file

  1. Give the notified bean (AccountService) to Spring administration.

    <bean id="accountService" class="com.main.service.impl.AccountServiceImpl"></bean>
    
  2. Configure the bean object for the facet class (Logger) and leave it to Spring because the facet class also needs to be generated as an object.

     <bean id="logger" class="com.main.utils.Logger"></bean>
    
  3. Use <Aop:config></Aop:config>Start configuring AOP

     <aop:config></aop:config>
    
  4. Use <Aop:aspect></Aop:aspect>Label configures which class to use as the facet class

     <aop:config>
            <aop:aspect id="logAdvice" ref="logger">
              ......
            </aop:aspect>
    </aop:config>
    
  5. Next, we can <Aop:aspect>In the label, write the notifications we need to configure, which are divided into five types

Let's start by describing how to write an entry point expression

Entry point expression

  • grammar

    Execution (expression)
    
  • Expression Writing

    • Example: public voidCom.main.service.Impl.AccountServiceImpl.saveAccount(int);
    • Correspondence: Access modifier return value package name. Package name. Package name.... Class name. Method name (parameter list)
  • Wildcard Writing of Expressions

    • Full wildcard notation: * *. *. *. *(..)), representing the method of any class
    • Be careful:
      • Access modifiers can be omitted
      • Return values, package names, class names, and method names can all be * denoted as arbitrary.(The package name here is just a few *)
      • A point between the package name and the class name that represents the class under the current package.The two points are the classes under the current package and its subpackages.
      • parameter list
        • Use...Indicates whether parameters are available
        • For base types: write names directly
        • Reference types: Write package names. How class names are writtenJava.long.String

Notification Classification

Before advice

Pre-notification, executed before the target method executes.By <Aop:before></Aop:before>Tags to configure.

Need to <Aop:aspect></Aop:aspect>Write Configuration Pre-Notification in Label

<aop:config>
        <aop:aspect id="logAdvice" ref="logger">
             <!--Pre-notification, where pointcut Refers to which method to assign pre-notifications-->
           <aop:before method="beforePrintLog" pointcut="execution(public void com.main.service.IAccountService.*(..))"></aop:before>
        </aop:aspect>
</aop:config>
  • Aop:aspectLabel
    • id attribute: name is optional
    • ref property: here is the bean object that references Logger above
  • Aop:beforeLabel
    • Method property: Refers to the method used to configure the Logger class as a preconfiguration.
    • The pointcut property: Inside is the entry point expression, and the methods used to point to which class need to configure the preceding methods (here are all methods of IAccountService).

after returning advise

Is executed after the entry point is executed normally.Only one of it and exception notifications is executed, because the post-executable represents the entire method is executed normally, with no exceptions.By <Aop:after></Aop:after>Tags to configure.

Need to <Aop:aspect></Aop:aspect>Write Configuration Post Notification in Label

<aop:config>
        <aop:aspect id="logAdvice" ref="logger">
           <aop:after method="afterPrintLog" pointcut="execution(public void com.main.service.IAccountService.*(..))"></aop:after>
        </aop:aspect>
</aop:config>

Attributes in tags mean the same thing as preceding notifications.

Exception Notification

Executes after an exception occurs at the entry point.Only one of them is executed, via <Aop:after-throwing></Aop:after-throwing>Tags to configure.

Need to <Aop:aspect></Aop:aspect>Write Configuration Post Notification in Label

<aop:config>
        <aop:aspect id="logAdvice" ref="logger">
           <aop:after-throwing method="throwPrintLog" pointcut="execution(public void com.main.service.IAccountService.*(..))"></aop:after-throwing>
        </aop:aspect>
</aop:config>

Attributes in tags mean the same thing as preceding notifications.

Return Notification

Returns the notification and executes after the target method returns the result.By <Aop:after-returning></Aop:after-returning>Tags to configure.

Need to <Aop:aspect></Aop:aspect>Write Configuration Post Notification in Label

<aop:config>
        <aop:aspect id="logAdvice" ref="logger">
           <aop:after-returning method="returnPrintLog" pointcut="execution(public void com.main.service.IAccountService.*(..))"></aop:after-returning>
        </aop:aspect>
</aop:config>

Attributes in tags mean the same thing as preceding notifications.

Around Advice

What is a surround notification?Literal means to execute around a method.

We know that the entire AOP implementation is similar to a dynamic proxy.The proxy can be enhanced on the original code.So what would a dynamic proxy look like if our saveAccount() method, for example, didn't use AOP?

Core Code Extract Here

//Generate Proxy Object
final IAccountService target = new AccountService();
//Generate Proxy Object
MyProxy myProxy = Proxy.newProxyInstance(IAccountService.getClass().getClassLoader(), new Class[] {IAccountService.class}, new InvocationHandler() {
			//When the target method is called, it is intercepted and brought under this method.
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				String methodName = method.getName();//Get method name
				Object result = null;
				try {
					//Pre-notification-------------------
					System.out.println("beforePrintLog Print logs...");
					result = method.invoke(target, args);//Execute Target Method
					//Post Notification------------------------------------------------------------------------------------------------------------------
					System.out.println("afterPrintLog Print logs...");
				} catch (Exception e) {
					//Exception Notification--------------------------------------------------------------------------------------------------------------
					System.out.println("throwPrintLog Print logs...");
				}
				//Return to Notification---------------
				System.out.println("returnPrintLog Print logs...");
				return result;//Returns the result of executing the target method
			}
			
		);

You can see that the various notifications of this AOP correspond to the printing location of the dynamic proxy above, but Spring is for convenience only by configuring it so that programmers do not need to connect to the dynamic proxy to write.

Instead of leveraging configurations for spring management, surround notifications are a way that the spring framework provides us with a way to manually control when enhancements are executed in code.You can refer to the code below to find similarities between surround notifications and dynamic proxies.

Our facet class configuration method around notifications is as follows:

 public Object aroundPrintLog(ProceedingJoinPoint proccedingJoinPoint){
        Object object = null;
        try {
            //Equivalent to Pre-Notification
            System.out.println("aroundPrintLog Print the log before...");
            Object[] args = proccedingJoinPoint.getArgs();
            object = proccedingJoinPoint.proceed(args);//Call business tier methods (entry point methods)
            //Equivalent to post-notification
            System.out.println("aroundPrintLog Then print the log...");
        } catch (Throwable throwable) {
            //Equivalent to exception notification
            System.out.println("aroundPrintLog XPrint log.........");
            throwable.printStackTrace();
        }finally {
            //Equivalent to final notification
            System.out.println("aroundPrintLog Final print log...");
        }
        return object;

    }

The Spring framework provides an interface: ProccedingJoinPoint.The interface has a method proceed(), which is equivalent to having a clear starting point method.

  •  This interface can be used as a parameter for wrapping notifications.The spring framework can provide us with implementation classes for this interface to use when the program executes
    

So how do you use it in XML?

By <Aop:around></Aop:around>Tags to configure.

Need to <Aop:aspect></Aop:aspect>Write Configuration Surround Notification in Label

<aop:config>
        <aop:aspect id="logAdvice" ref="logger">
           <aop:around method="aroundPrintLog" pointcut="execution(public void com.main.service.IAccountService.*(..))"></aop:around>
        </aop:aspect>
</aop:config>

Attributes in tags mean the same thing as preceding notifications.

Keywords: Spring Java Attribute xml

Added by stevegg1965 on Mon, 29 Jun 2020 19:52:45 +0300