1.IOC and AOP concepts
IOC: Inversion of control, the object creation and the calling process between objects, Let Spring manage it. The purpose of using IOC is to reduce coupling.
AOP: Aspect-oriented programming, a technology that achieves unified maintenance of program functions through pre-compilation and dynamic proxies during runtime. AOP is the continuation of OOP, a hot spot in software development, an important content in the Spring framework, and a derivative paradigm of functional programming. AOP can be used to isolate various parts of the business logic, thereby reducing the coupling between the various parts of the business logic, improving the reusability of the program, and improving the efficiency of development. The underlying implementation of AOP is based on dynamic proxy (the implementation method is to use the JDK native dynamic proxy when switching to the interface; when switching to the ordinary method, use the cglib dynamic proxy).
2. Why use dynamic proxy
With the continuous expansion of business:
(1) Log function: If the log code is modified, many modifications need to be made.
(2) Verification function: If multiple places need to be verified, multiple changes need to be made.
At this time, you need to use a dynamic proxy to solve the problem. There are two ways to implement dynamic proxy:
[1]JDK native dynamic proxy: The disadvantage is that it must be completed based on the interface
[2]cglib dynamic proxy: It can be completed without interface-based
2.1 JDK native dynamic proxy
2.1.1 MathService interface class
public interface MathService { //+ public Double add(double a,double b); //- public Double sub(double a,double b); //* public Double mul(double a,double b); /// public Double div(double a,double b); }
2.1.2 MathServiceImpl implementation interface class
public class MathServiceImpl implements MathService{ @Override public Double add(double a, double b) { Double result=a+b; return result; } @Override public Double sub(double a, double b) { Double result=a-b; return result; } @Override public Double mul(double a, double b) { Double result=a*b; return result; } @Override public Double div(double a, double b) { Double result=a/b; return result; } }
2.1.3 ProxyFactory dynamic proxy factory
public class ProxyFactory { //被代理对象 private Object target; public ProxyFactory(Object target) { this.target = target; } //获取代理对象 public Object getProxy(){ /** * ClassLoader loader, 被代理对象的类加载器 * Class<?>[] interfaces, 被代理对象实现的接口 * InvocationHandler h: 当代理对象执行被代理的方法时,会触发该对象中的invoke功能 */ ClassLoader loader=target.getClass().getClassLoader(); Class<?>[] interfaces=target.getClass().getInterfaces(); InvocationHandler h=new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //可以加上需要的非业务代码 //method.getName()获取方法名 // Arrays.asList(args)获取输入值 System.out.println("this is "+method.getName()+" method begin with"+ Arrays.asList(args)); //method:表示代理对象要代理的方法 //invoke:回调该函数 //args:方法需要的参数 Object result = method.invoke(target, args);//代理对象回调该方法 return result; } }; //先写此处方法,才可找到上述三个方法填写方式 Object o = Proxy.newProxyInstance(loader, interfaces, h); return o; } }
2.1.4 Test class
public class Test01 { public static void main(String[] args) { MathServiceImpl target=new MathServiceImpl(); ProxyFactory proxyFactory=new ProxyFactory(target); MathService proxy = (MathService) proxyFactory.getProxy(); Double add = proxy.add(15.0, 5.0); System.out.println(add); } }
2.2 cglib dynamic proxy
2.2.1 MathServiceImpl class
public class MathServiceImpl{ public Double add(double a, double b) { Double result=a+b; return result; } public Double sub(double a, double b) { Double result=a-b; return result; } public Double mul(double a, double b) { Double result=a*b; return result; } public Double div(double a, double b) { Double result=a/b; return result; } }
2.2.2 ProxyFactory dynamic proxy factory
Note:
(1) Introduction The jar package of cglib.
cglib
cglib
3.2 .5
(2) Create a proxy class factory and implement the interface MethodInterceptor
public class ProxyFactory implements MethodInterceptor { private Object target; public ProxyFactory(Object target) { this.target = target; } //获取代理对象 public Object getProxy(){ Enhancer enhancer=new Enhancer(); //指定被代理对象的父类 enhancer.setSuperclass(target.getClass()); //指定回调类 enhancer.setCallback(this); //创建代理对象 return enhancer.create(); } //当代理对象执行代理方法时触发的方法 public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { // System.out.println("before++++++++++++++++++++"); // Object result = method.invoke(target, args); //可以加上需要的非业务代码 //method.getName()获取方法名 // Arrays.asList(args)获取输入值 System.out.println("this is "+method.getName()+" method begin with"+ Arrays.asList(args)); //method:表示代理对象要代理的方法 //invoke:回调该函数 //args:方法需要的参数 Object result = method.invoke(target, args);//代理对象回调该方法 return result; } }
2.2.3 Test class
public class Test01 { public static void main(String[] args) { MathServiceImpl target=new MathServiceImpl(); ProxyFactory proxyFactory=new ProxyFactory(target); MathServiceImpl proxy = (MathServiceImpl) proxyFactory.getProxy(); Double add = proxy.add(1, 2); System.out.println(add); } }
3.AOP dynamic proxy
3.1 Add corresponding dependencies
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.15.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.2.15.RELEASE</version> </dependency>
3.2 Configure spring.xml file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--包扫描--> <context:component-scan base-package="com.qy151wd.proxy.proxy.aop"/> <!--开启aop注解--> <aop:aspectj-autoproxy/> </beans>
3.3 MathService Interface class
public interface MathService { public Double add(double a, double b); public Double sub(double a, double b); public Double mul(double a, double b); public Double div(double a, double b); }
3.4 MathServiceImpl implementation interface class
@Service public class MathServiceImpl implements MathService { @Override public Double add(double a, double b) { Double result=a+b; return result; } @Override public Double sub(double a, double b) { Double result=a-b; return result; } @Override public Double mul(double a, double b) { Double result=a*b; return result; } @Override public Double div(double a, double b) { Double result=a/b; return result; } }
3.5 LogAspect class
@Service //若是使用@component也可以 @Aspect //表示该类为切面类 public class LogAspect { //任意返回类型 aop包下的所有类都有切面日志 使用通配符 //第一个*:修饰符和返回值类型 //第二个*:所有类 //第三个*:所有方法 @Before("execution(* com.qy151wd.proxy.proxy.aop.*.*(..))") public void before(){ System.out.println("方法执行前的日志"); } @After("execution(* com.qy151wd.proxy.proxy.aop.*.*(..))") //总会被执行,不管有没有异常 public void after(){ System.out.println("方法执行后的日志"); } @AfterReturning("execution(* com.qy151wd.proxy.proxy.aop.*.*(..))")//只有碰到return后才会执行 public void afterReturning(){ System.out.println("碰到return后执行"); } @AfterThrowing("execution(* com.qy151wd.proxy.proxy.aop.*.*(..))")//异常通知 public void afterThrowing(){ System.out.println("出现异常了"); } }
3.6 Test class
public class Test01 { public static void main(String[] args) { //从spring容器中获取 ApplicationContext app=new ClassPathXmlApplicationContext("spring.xml"); MathService mathService = (MathService) app.getBean("mathServiceImpl"); Double add = mathService.add(10, 5); System.out.println(add); } }
The above is the detailed content of What is Java AOP dynamic proxy?. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor