IOC and AOP of Spring system

Foreword

Spring is a lightweight Inversion of Control (IoC) and Aspect-Oriented (AOP) container framework.

IOC

1. Concept of IOC

Inversion of Control (IoC=Inversion of Control) IoC, in vernacular terms, means that the container controls the (dependency) relationship between programs, instead of being directly controlled by program code in traditional implementations. This is the so-called “inversion of control” concept: (dependency) control is transferred from the application code to the external container. The transfer of control is the so-called inversion.

IoC also has another name: “Dependency Injection (DI=Dependency Injection)”, that is, the container dynamically injects certain dependencies into the component.

Case: Implementing Spring’s IoC

IOC/DI

Hands over the work of object instantiation/assignment that was previously done by programmers to spring

2. Application of IOC

The commonly used implementation of Spring IoC container is ApplicationContext, which is an IoC container with rich functions. By defining Bean information in the configuration file or using annotations for configuration, the application can use the ApplicationContext to obtain the required Bean instances and make use of the functions provided by the container, such as AOP (aspect-oriented programming), transaction management, etc.

3. Characteristics of IOC

Spring IoC achieves decoupling and flexibility between objects by handing over the creation, assembly and management tasks of objects to the container. It simplifies application development and maintenance and improves code reusability and testability. At the same time, Spring IoC also provides a wealth of functions and extension points, making it easier for developers to develop enterprise-level applications.

4.The underlying logic of IOC

The bottom layer of IoC uses factory mode, Java’s reflection mechanism, XML parsing and other technologies to reduce the coupling of the code to the minimum. The main steps are as follows.

  1. In the configuration file (such as Bean.xml), configure each object and the dependencies between them;
  2. We can think of the IoC container as a factory, and the product of this factory is Spring Bean;
  3. When the container starts, it will load and parse these configuration files to obtain basic information about the objects and the dependencies between them;
  4. IoC uses Java’s reflection mechanism to generate a corresponding object (i.e. Spring Bean) based on the class name, and injects this object into objects that depend on it based on dependencies.

5.IOC injection method

a.set inject property name value ref

Basic data injection

String

Custom type injection (commonly used in opening)

b.Construction injection construct-arg

c.Automatic assembly

byName Go to the spring context based on the attribute name in the current Bean object

byType automatically finds the implementation class in the spring context based on the interface.

AOP

1. Concept of AOP

Spring AOP (Aspect-oriented Programming) is an important feature provided by the Spring framework, which is used to achieve modularity and reusability of cross-cutting concerns. It decouples cross-cutting concerns from core business logic without modifying the original business logic code, and defines and manages these concerns through aspects.

In traditional object-oriented programming, business logic code is usually scattered among various objects, while cross-cutting concerns (such as logging, transaction management, security control, etc.) are intertwined, resulting in code duplication and difficulty in maintenance. Spring AOP treats cross-cutting concerns as an independent module, called aspects, and uses a mechanism called pointcut to select which connection points (Joinpoints) to apply aspects on.

AOP – Aspect Oriented Programming

2.The core of AOP

The core concepts of Spring AOP include the following:

  1. Target: the object to be notified (proxied)

  2. Joinpoint: A joinpoint is a point where aspects can be inserted during program execution. For example, method invocation, method execution, field access, etc.

  3. Advice: Advice defines the behavior that an aspect performs on a join point. Including pre-notification (Before), post-notification (After), return notification (After-returning), exception notification (After-throwing) and surrounding notification (Around).

  4. Proxy: An object created after applying a notification to the target object (Proxy = target + notification),

  5. Pointcut: Pointcut uses expressions or annotations to select which connection points to apply aspects on. The connection point can be the execution of a method, the invocation of a method, the access of a field, etc.

  6. Adapter (Advisor): Adapter = Notification (Advice) + Pointcut (Pointcut)

  7. Aspect: Aspect is a modular and reusable unit that cuts across concerns. It consists of pointcuts, notifications, and other configuration elements. Aspects define at which connection points a specific behavior should be performed.

Spring AOP can be seamlessly integrated with the Spring IoC container. Aspects are defined as beans through configuration files or annotations, and the container is responsible for management and application. The implementation of Spring AOP is based on dynamic proxy technology. You can use JDK dynamic proxy or CGLIB bytecode generation library to create proxy objects.

3.AOP agent

The tool class org.springframework.aop.framework.ProxyFactoryBean is used to create proxy objects, and in general the following three properties need to be injected:

  1. proxyInterfaces: List of interfaces (List) that the proxy should implement. This attribute specifies a list of interfaces that the proxy object should implement. By implementing these interfaces, the proxy object can provide the same interface methods as the target object.

  2. interceptorNames: The names (List) of notification beans that need to be applied to the target object. This attribute specifies a list of notification bean names that should be applied to the target object. A notification bean is an object that implements aspect logic, which defines operations to be performed on specific connection points of the target object.

  3. target: target object (Object). This attribute specifies the target object to be proxied, that is, the actual business object that needs to be proxied.

By setting the above three properties, ProxyFactoryBean can create a proxy object according to the configuration. The proxy object can have the same interface as the target object and apply notification logic before and after method calls.

<bean id="targetObject" class="com.example.TargetObject" />

<bean id="adviceBean" class="com.example.AdviceBean" />

<bean id="proxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="proxyInterfaces">
        <list>
            <value>com.example.TargetInterface</value>
        </list>
    </property>
    <property name="interceptorNames">
        <list>
            <value>adviceBean</value>
        </list>
    </property>
    <property name="target" ref="targetObject" />
</bean>

ProxyFactoryBean creates a proxy object that implements the com.example.TargetInterface interface and applies an advice bean named adviceBean. The target object being proxied is targetObject.

By configuring ProxyFactoryBean, we can decouple the aspect logic (adviceBean) from the target object (targetObject), and finally get a proxy object that can execute the notification logic before and after the method call of the target object.

ProxyFactoryBean provides a simple and flexible way to implement AOP and dynamic proxies, which can help us achieve cross-cutting separation of concerns in applications and increase code maintainability and reusability.

4.AOP notification types

Pre-advice: Advice() executed before the join point

Implement the org.springframework.aop.MethodBeforeAdvice interface

Add system logs before buying books and commenting

Post-notification: A notification that executes after the join point completes normally

Implement the org.springframework.aop.AfterReturningAdvice interface

Rebate for buying books (bug exists)

Surround notification: A notification that surrounds a connection point. The biggest feature is that the return value can be modified. Since it adds its own logic code before and after the method, it is extremely powerful.

org.aopalliance.intercept.MethodInterceptor

Similar to an interceptor, it will include entry points, and code will be executed before and after the target class.

Exception notification: This notification will be executed when the method throws an exception and exits.

org.springframework.aop.ThrowsAdvice

If an exception occurs, execute the system prompts and then handle it. Price anomalies as an example

Filter notifications (adapter): adapter = notification (Advice) + pointcut (Pointcut)

org.springframework.aop.support.RegexpMethodPointcutAdvisor

Dealing with the bug of rebate for book purchase

Interview questions

1, Spring’sIOCandAOPmechanism?

we are using
Spring
The process of framing is actually to use
IOC
, dependency injection, and
AOP
, aspect-oriented programming, these two

One is
Spring
soul.
The main design patterns used are factory pattern and proxy pattern.

IOC
It is a typical factory model, through
sessionfactory
to inject the instance.

AOP
It is the embodiment of the typical agency model.

Proxy mode is commonly used
java
Design pattern, its characteristic is that the proxy class and the delegate class have the same interface, the proxy class is mainly responsible for the delegate class

Preprocess messages, filter messages, forward messages to delegate classes, and process messages afterwards. There is usually a relationship between proxy classes and delegate classes

Association relationship, an object of a proxy class is associated with an object of a delegate class. The object of the proxy class itself does not actually implement the service, but passes the

Provide specific services by calling related methods of objects of the delegate class.

spring
of
IoC
Container is
spring
Core,
spring AOP
Yes
spring
An important part ofthe framework.

In traditional programming, when the caller needs assistance from the callee, the caller usually creates an instance of the callee. But in

spring
The work of creating the callee is no longer done by the caller, so control is inverted (
IoC
); Create a work pass for the callee instance

Changyou
spring
The container completes it and then injects it into the caller, so it is also called dependency injection (
DI
), dependency injection and inversion of control are the same

a concept.

Aspect Oriented Programming (
AOP)
It considers the program structure from another angle and improves object-oriented programming by analyzing the concerns of the program structure.

(
OOP
).
OOP
Decompose the application into various levels of objects, and
AOP
Break the program into multiple aspects.
spring AOP
Only true

A method-level join point appears, in
J2EE
In application,
AOP
Intercepting operations down to the method level is sufficient. exist
spring
in, the future makes

IoC
Conveniently use robust, flexible enterprise services you need to take advantage of
spring AOP
implemented as
IoC
Establish connections with enterprise services.

IOC:
Inversion of control is also called dependency injection. Utilizing factory pattern

To hand over the object to container management, you only need to
spring
Configuration files are always configured accordingly
bean
, and set the relevant properties so that

spring
Container to generate instance objects and management objects of classes. in
spring
When the container starts,
spring
Puts you in the profile

Configured in
bean
Initialize them all, and then when you need to call them, use the ones that have been initialized
bean
Assigned to your needs

Call these
bean
‘s class (assuming the class name is
A
), the allocation method is to call
A
of
setter
Method to inject without requiring you to

A
Inside
new
These
bean
Then.

Note: During the interview, if possible, draw a picture to make it more obvious that you understand
.

spring ioc
Initialization process

AOP:
Aspect-oriented programming. (
Aspect-Oriented Programming
)

AOP
That’s right
OOP
Supplement and improvement.
OOP
Introducing concepts such as encapsulation, inheritance and polymorphism to establish an object hierarchy,

A collection used to simulate public behavior. When we need to introduce public behavior to dispersed objects,
OOP
It seems powerless.

In other words,
OOP
Allows you to define relationships from top to bottom, but is not suitable for defining relationships from left to right. For example, the logging function. Log generation

Code tends to be spread horizontally across all object hierarchies, having nothing to do with the core functionality of the objects to which it is spread. in
OOP
Designing it

Resulting in a large amount of code duplication, which is not conducive to the reuse of various modules.

Encapsulate the cross-business logic in the program (such as security, logging, transactions, etc.) into an aspect, and then inject it into the target object (specific

Business logic).

Implementation
AOP
The technology is mainly divided into two categories: one is the use of dynamic proxy technology, which uses the method of intercepting the message to install the message

Decoration to replace the execution of the original object behavior; the second is to use static weaving to introduce specific syntax creation

Aspects

so that the editor

The translator can weave in relevant information during compilation

Aspects

code
.

Explain it simply, let’s say you want to
biz
Add a print to all classes of the layer

Hello

function
,
You can use it now
aop
Thoughts to do
.

You first write a class and a class method, and the method is printed after implementation

Hello
‘,
Then
ioc
this class
ref
=
“biz.*”
This can be achieved by injecting each class.

2. There are several methods of dependency injection. What are they? ?

1. Constructor injection

Inject the dependent object into the dependent object through the parameters of the constructor, and inject it when initializing the object.

advantage:

After the object initialization is completed, the usable object can be obtained.

shortcoming:

When there are many objects to be injected, the constructor parameter list will be very long;

Not flexible enough. If there are multiple injection methods, and each method only needs to inject a few specified dependencies, then multiple overloaded constructors need to be provided.

Number, trouble.

2.
setter
Method injection

IoC Service Provider
Provided by calling member variables
setter
The function will be injected into the dependent class by the dependent object.

advantage:

flexible. Required objects can be selectively injected.

shortcoming:

After the dependent object is initialized, it cannot be used because the dependent object has not been injected yet.

3. Interface injection

The dependent class must implement the specified interface, and then implement a function in the interface, which is used for dependency injection. The parameters of this function

The number is the object to be injected.

advantage

In interface injection, the name of the interface and the name of the function are not important, as long as the parameters of the function are of the type of object to be injected.

shortcoming:

The intrusive behavior is too strong and is not recommended.

P.S.
: What is an intrusion?

if class
A
To use a function provided by others, if in order to use this function, you need to add additional code to your own class, this is

Invasive.