Principles of IOC and AOP in Spring

IOC (Inversion of Control) Inversion of Control

IoC is a Java programming pattern. For the spring framework, IoC means that spring is responsible for controlling the life cycle of objects and the relationship between objects. After the IOC container, the control of creating and finding dependent objects is handed over to the container, and the container injects the combined object, so the objects are loosely coupled, which is also convenient for testing, conducive to function reuse, and more importantly, makes The whole architecture of the program becomes very flexible.

DI (Dependency Injection) is "Dependency Injection": through the dependency injection mechanism, we only need to specify the resources required by the target through simple configuration without any code, and complete our own business logic without the need for specific resources. who provided it.

IoC is the core of Spring, throughout. For the Spring framework, Spring is responsible for controlling the life cycle of objects and the relationship between objects.

There are two ways to implement DI in Spring—Setter way (passing value mode) and constructor way (reference mode).

Three injection methods

  • XML: The Bean implementation class comes from a third-party class library, such as DataSource, etc. Configuration such as namespace is required, for example: context, aop, mvc.
  • Annotations: Use annotations such as @Controller, @Service, etc. in the developed class
  • Java Configuration Class: A scenario where object creation logic is controlled through code. For example: custom modification of dependent class libraries.

AOP (Aspect-Oriented Programming) aspect-oriented programming

Add new functions to the main function without modifying the source code.

The underlying principle of AOP

The bottom layer of aop uses dynamic proxy (two cases)

  • If there is an interface, use jdk dynamic proxy

    Create an interface implementation class object to enhance the methods in the class

  • If there is no interface, use CGLIB dynamic proxy

    Create a proxy object of the subclass to enhance the method in the class

aop dynamic proxy implementation (jdk)

  • Use jdk dynamic proxy to create a proxy object using the method in the Proxy class

The three parameters of newProxyInstance: (1) class loader; (2) the class where the enhanced method is located, the interface implemented by this class supports multiple interfaces; (3) implement this interface InvocationHandler, create a proxy object, and write the enhanced method

  • jdk dynamic proxy code
    • create interface, define method
    • Create an interface implementation class and implement the method
    • Use proxy class c

Implement interfaces based on anonymous inner classes;

Guess you like

Origin blog.csdn.net/qq_39756007/article/details/129012455