1. What problem does the Spring container solve

Advantages:

  1. Low coupling for code architecture from top to bottom. Spring supports interface injection, and when you change code logic, you can switch seamlessly by changing the implementation class.
  2. OOP decomposes business programs into objects at various levels and accomplishes business through object linkage

Disadvantages:

  1. Inability to address common system requirements scattered across businesses. For example: code logging, service function permission verification, caching, transaction management… Prone to code intrusion, increase coupling and maintenance costs.

2. Programming for facets

Aspect Oriented Programming, that is, we often say AOP. It complements OOP by providing a technique for enhancing functionality both at compile time and at run time. In OOP, each unit module is a Class, whereas AOP focuses on unit modules as aspects. For example, the @Transactional annotation on transaction management marks methods that perform Transactional operations at the beginning and end of such methods.

As you can see from the diagram, when addUser adds @Transactional, operations involving a database are broker-handled by transaction-managed classes. Spring develops a framework for Spring AOP based on AspectJ, providing faceted programming capabilities based on schema or @AspectJ annotation style. Within the framework, there are a number of declarative faceted services: @Transactional, @async, @cacheable… Alternatively, users who want to customize their own facets can program using the Spring AOP framework.

Note that AOP is an idea and is not unique to Spring.

2.1 Concepts in aspect programming

To understand AOP, you need to understand some of the concepts commonly used in AOP:

  • Aspect:Aspect, the modular unit in AOP that encapsulates aspect logic. inSpring AOPIn, facets often exist in the form of classes or XML.

For example, if you need to do a facet to a system log, then you need to write a class that describes the logic in it. That class is an Aspect.

  • Join point:Join point, a point in the execution of a program. inSpring AOPIn, join points always represent method execution.
  • Advice:Notification, that is, the timing of execution at a particular join point slice.Spring AOPprovidesAround,Before,AfterThe timing of the execution of the aspect logic.
  • Pointcut:Pointcuts, join points represent all the places where the aspect logic can be applied, and pointcuts correspond to places where the aspect logic needs to be applied,Spring AOPSupport the use ofAspectJTo specify a pointcut.

Here’s an example that might get a little convoluted: Suppose there are three methods in a class, and all three can be used as join points for the aspect. If only one of these methods needs to do the aspect logic, then that method is our starting point.

  • Introduction:Introduce a new interface into an object surrounded by aspect logic. inSpring AOPMedium, yesintroductionTo “introduce” a new interface into the cut class.
  • Target object:Objects surrounded by aspect logic. inSpring AOPIn, classes surrounded by aspect logic are usually proxied, or proxied objects.
  • AOP proxy:Objects created by an AOP framework to implement AOP logic. inSpring AOPIn, two proxies are supportedJDK dynamic proxyandAdditional agent
  • Weaving:Links the slice to the proxied object.Spring AOPPerform weaving logic at run time.
Advice in Spring AOP
Advice (notice) describe
Before advice Pre-notification, executed before the join point, does not affect the overall execution flow unless an exception is thrown.
After returning advice Post-notification, executed after the join point returns normally (this notification is not executed if an exception is thrown).
After throwing advice Executes after an exception is thrown at a join point
After (finally) advice This notification (equivalent to finally in try Finally) is executed whether or not the join point executes normally.
Around advice Circular notifications do all of the things described above. Imagine being proxied by means ofa(), so the surround can be righta()dotry catch finallyCircular notification is the most common type of notification.

Since Around Advice covers all advice, why does Spring AOP need to declare so much advice? The official word is to recommend using the smallest level of advice to meet your needs.

For example, if only one log operation was required for each method input, then before advice would suffice, and around advice would not be required.

2.1.2 Advice Execution Sequence

Conclusion :Spring has tweaked the @after execution order since 5.2.7. As shown: officially follows the semantics of AspectJ. Let me go to

Before 5.2.7, Spring AOP according to @ Around, @ Before, After, AfterReturning, AfterThrowing sequentially.

2.2 Start simple AOP programming

  • Create a simple service as the proxied object
package com.xjm.service.impl;

import com.xjm.service.HelloService;
import org.springframework.stereotype.Service;

/ * * *@author jaymin
 * 2020/11/26 17:04
 */
@Service
public class HelloServiceImpl implements HelloService {

	@Override
	public String hello(a) {
		return "Hello,Spring Framework!"; }}Copy the code
  • Write the aspect class
package com.xjm.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.logging.Logger;

/ * * *@authorJaymin. <br> * System foundation section, mainly used for research on AOP
@Aspect
@Component
public class SystemServiceAspect {

	private static final Logger log = Logger.getGlobal();

    /** * uses constants to manage pointcuts */
    public static final String SYSTEM_SERVICE_POINT_CUT = "systemServicePointCut()";

    /** * 

Pointcut can use expressions to specify pointcuts. *

Execution is an expression. service.. *. * (..)

*

means that all methods (including arbitrary arguments) of all classes in the service package under the com.xjm package are intercepted */

@Pointcut("execution(* com.xjm.. service.. *. * (..) )" public void systemServicePointCut(a) {}/** * before the method is executed@param joinPoint */ @Before(SYSTEM_SERVICE_POINT_CUT) public void before(JoinPoint joinPoint) { log.info("before method execute "); } /** * wrap around the execution of the entire method *@param joinPoint * @return* / @Around(SYSTEM_SERVICE_POINT_CUT) public Object around(JoinPoint joinPoint) { LocalDateTime startTime = LocalDateTime.now(); log.info("around method starts "); Object result; try { result = ((ProceedingJoinPoint) joinPoint).proceed(); } catch (Throwable throwable) { throw new RuntimeException(throwable); } finally { LocalDateTime endTime = LocalDateTime.now(); long executeTime = Duration.between(startTime, endTime).toMillis(); log.info("method end."); } return result; } /** * the method returns the value@param joinPoint * @param result */ @AfterReturning(pointcut = SYSTEM_SERVICE_POINT_CUT, returning = "result") public void afterReturning(JoinPoint joinPoint, Object result) { log.info("method return"); } /** * after the method throws an exception@param joinPoint * @param exception */ @AfterThrowing(pointcut = SYSTEM_SERVICE_POINT_CUT, throwing = "exception") public void afterThrowing(JoinPoint joinPoint, Exception exception) { log.info("current method throw an exception,message"); } /** * get join point method name *@param joinPoint * @return* / public String getMethodName(JoinPoint joinPoint) { return ((MethodSignature) joinPoint.getSignature()).getMethod().getName(); } /** * after the method is executed@param joinPoint */ @After(SYSTEM_SERVICE_POINT_CUT) public void after(JoinPoint joinPoint) { log.info("after method execute"); }}Copy the code
  • Execute hello

Note that Spring does not enable AOP by default. If you are using SpringBoot, add @enableAspectJAutoProxy to the boot class.

Result:

February 13, 2021 10:42:38 afternoon com. XJM. Aop) SystemServiceAspect around information: Around method starts on February 13, 2021 com 10:42:38 afternoon. XJM. Aop) SystemServiceAspect before information: Before method execute February 13, 2021 com 10:42:38 afternoon. XJM. Aop) SystemServiceAspect around information: method end. February 13, 2021 10:42:38 afternoon com. XJM. Aop) SystemServiceAspect after information: After method execute February 13, 2021 com 10:42:38 afternoon. XJM. Aop) SystemServiceAspect afterReturning information: method returnCopy the code

The author uses the Spring 5.1.x version

conclusion

  • Spring AOP further enhances OOP by providing a framework capability for faceted programming in pluggable form.
  • AOP is another programming idea with a mature system and its own terminology.
  • AOP can weave in program functionality either through precompilation or through run-time dynamic proxies.
  • Spring AOP only supports method execution join points and uses JDK dynamic proxies and CGLIB proxies internally to support AOP.