Simple implementation of IOC principle of spring

Inversion of control (IOC for short)

Simply put, when you need an object, you don't need to manually create a new one, but other containers will help you provide it; Spring is the IOC container.

For example:

In spring, it is often necessary to assemble a Dao in the service, generally using @ Autowired annotation: similar to the following

If you use DAO uninitialized directly here, null pointer exceptions will be reported. The way in spring is to load the required classes for you through reflection.

The following is an example that simulates spring's Di and IOC

First, write two annotations to simulate spring's annotations:

After the annotation is created, two classes are created: the rain class represents the need to obtain weather data (database or server) from other places

The weather class represents the obtained weather data

The following is direct injection through reflection:

First, traverse the specified package name: this step is omitted first,

The first step is to create a list bean container that simulates spring, that is, initialize all the initialized classes with entity annotations

Finally, it is directly used in the simulation controller

There is no new operation on rain in weatherprediction, but it can be used. This should be the simplest IOC example simulating spring. Of course, the IOC container of spring is much more powerful than this, such as thread safety and various details

summary

The above is all about the detailed explanation of the IOC principle of simple implementation of spring in this paper. I hope it will be helpful to you. Interested friends can continue to refer to this website:

Detailed explanation of spring IOC principle

Simple understanding of spring IOC and AOP and code examples

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>