preface

AOP is also a relatively important content in Spring. Compared with traditional OOP pattern, AOP has many difficult places to understand. This article will introduce the implementation method of AOP and its underlying implementation, including:

  • The initial AOP
  • The basic concepts of AOP
  • AOP Concepts terminology
  • A dynamic proxy
  • Notification introduction (pre, post, return, exception, surround)
  • Configure notifications based on annotations

What is AOP

AOP(aspect-oriented Programming), that is, Aspect Oriented Programming, which is complementary to OOP(Object-oriented Programming), Provides a different perspective on abstract software structures from OOP where we use classes as our base unit, whereas in AOP the base unit is aspects

Second, the basic concepts of AOP

An AOP framework has two characteristics:

Good isolation between steps.

Source code independence.

AOP Concepts

Aspect/Advisors (Section)

Modularity of a concern that may crosscut multiple objects. In Spring AOP, aspects can be implemented using pattern-based or @aspect-based annotations.

Join point

A point during the execution of a program. In Spring AOP, join points always represent method execution.

Advice (Advice)

An action performed at a specific join point in a section. Many AOP frameworks, including Spring, base their notification model on interceptors and maintain a chain of interceptors centered around join points.

Pointcut

Find conditions at join points. Advice is associated with a pointcut expression and runs at join points that satisfy that pointcut.

Introduction

Declare additional methods or attributes for a type. Spring allows you to introduce new interfaces (and a corresponding implementation) to any proxied object.

Target object

An object notified by one or more facets. Also called an informed person. Since Spring AOP is implemented through a runtime proxy, this object is always a proxied object.

AOP proxy

An object created by an AOP framework to implement aspect contracts (such as notifying method execution, and so on). In Spring, an AOP proxy can be either a JDK dynamic proxy or a CGLIB proxy.

Weaving (Weaving)

Weaving is the process of creating an AOP proxy object by applying aspects to the target object. Weaving can occur at compile time, class load time, or run time.

Spring AOP

Spring AOP uses a pure Java implementation, which does not require a specialized compilation process. Spring AOP does not need to control the classloader hierarchy, so it is suitable for Servlet containers or application servers.

Spring AOP currently only supports method execution join points.

Spring implements AOP differently than other frameworks. Spring is not intended to provide the most complete AOP implementation (although Spring AOP has that capability). Instead, it focuses on providing an integration between an AOP implementation and the Spring IoC container to help solve common problems in enterprise development.

Spring AOP was never intended to compete with AspectJ by providing a comprehensive AOP solution. We believe that either proxy-based frameworks such as Spring AOP or mature frameworks such as AspectJ are valuable and should complement rather than compete with each other.

The underlying implementation of Spring framework AOP

The AOP technology of Srping framework is also the proxy technology, which provides two ways of proxy

Dynamic proxy based on JDK

Must be interface oriented; only classes that implement a concrete interface can generate proxy objects

CGLIB based dynamic proxy

For classes that do not implement interfaces, proxies can also be generated, in the form of subclasses of that class

Spring’s traditional AOP uses different approaches to proxying, depending on whether a class implements an interface

If you implement class interfaces, use JDK dynamic proxies for AOP

. If there is no implementation interface, use CGLIB dynamic proxy to accomplish AOP

For classes that do not implement interfaces, proxies can also be generated, in the form of subclasses of that class

Spring’s traditional AOP uses different approaches to proxying, depending on whether a class implements an interface

If you implement class interfaces, use JDK dynamic proxies for AOP

If no interface is implemented, CGLIB dynamic proxies are used for AOP

Simple implementation of AOP based on Spring

To successfully run code with Spring AOP, it is not enough to use only the jar packages provided by Spring for developers. Please download two additional JAR packages online:

1, aopalliance. Jar

2, aspectjweaver. Jar

Implement AOP notification effect through configuration

The XML configuration

<bean id="logger" class="com.ahpome.company.utils.Logger" /> <aop:config> <aop:aspect id="loggerAspect" ref="logger"> // < AOP :pointcut ID ="loggerRef" expression="execution(* com.ahpome.company.. *. * (..) ) and ! <aop:around method="record" pointcut-ref="loggerRef" /> // Before; Post notification :after; Final Notice: After-Returning; Java public Object Record (ProceedingJoinPoint PJP){Log Log = new  Log(); try { log.setOperator("admin"); String mname = pjp.getSignature().getName(); log.setOperName(mname); Object[] args = pjp.getArgs(); log.setOperParams(Arrays.toString(args)); Proceed (); // Proceed (); // Proceed (); if(obj ! = null){ log.setResultMsg(obj.toString()); }else{ log.setResultMsg(null); } log.setOperResult("success"); System.out.println("1111"); return obj; } catch (Throwable e) { log.setOperResult("failure"); log.setResultMsg(e.getMessage()); } finally{ // logService.saveLog(log); } return null; Note: this method returns null even if you call it null, even if your method has a return value}}Copy the code

JDK dynamic proxy

Public interface UserService {void save(); int select(); Public class UserServiceImpl implements UserService {@override public void save() { System.out.println(" Saved user info successfully "); } @override public int select() {system.out.println (); return 10; Public class javkProxyFactory implements InvocationHandler {private Object target; public JdkProxyFactory(Object target) { this.target = target; } /** * get the proxy object, Public Object getProxyObject() {return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// Add function system.out.println (" enhance code, add logging function "); // Invoke method.invoke(target, args); }}Copy the code

Test the JDK dynamic proxy

@test public void JdkProxyTest() {// create target object UserService UserService = new UserServiceImpl(); JdkProxyFactory = new JdkProxyFactory(userService); UserService proxy = (UserService) jdkProxyFactory.getProxyObject(); proxy.save(); System.out.println("========================="); proxy.select(); }Copy the code

conclusion

Above is my Java development of large Internet architecture Spring AOP implementation principle of Spring AOP underlying implementation problems and optimization summary.

That’s the end of the article

Xiaobian here summarizes a Spring AOP mind map, want to understand the small partner can look at it

Like xiaobian to share technical articles can like attention oh!

Here are some spring technology buckets and interview questions

Public account: Kylin bug