The creation and use of Spring

Table of contents

1. What is Spring

IoC

2. Spring creation and use

Create Spring

access bean

The difference between BeanFactory and ApplicationContext

3. Summary


 

1. What is Spring

spring official website: spring.io

aaf7108dbc794eb7b9c8108d7fc1a8b6.png

Its ecology is very perfect

b1f46fb3f9a94feb9e11b64919e4709c.png

Generally speaking, Spring refers to the Spring Framework (Spring Framework), which is an open source framework that supports a wide range of application scenarios and makes Java enterprise application development easier.

Spring Framework is the most basic project in the Spring ecosystem and the foundation of other projects

Core: Spring is an IoC container that contains many tools and methods

So what is an IoC container?

Container: List/Map=>data storage container, tomcat=>web container, etc. that I learned before are all containers

Spring=>IoC container

IoC

IoC: Inversion of Control control inversion, Spring is an inversion of control container

So what exactly is IoC?

This starts with the current situation of our Java code writing. In traditional programming, the coupling between objects is relatively high.

Let's write an example, the Test class depends on the A class to complete the task, and A depends on B to complete the task

2bc5bc983f51461484b9be05ab0cfaad.png

Create class A 

The A object is dependent on the B object, so an error will be reported

cd7eb514127b42f1860addeb66317509.png

plus class B

a9b5ecfc2ba2423b8ccd33e2dfa0eb58.png

At this time, class A no longer reports an error

cdfe3f2a655942bba8df47392d081f46.png

That is, when object A wants to use object B, it needs to create a new object B. At this time, object A has control over object B. When the party is using it, it can set B to null and it will be recycled.

A depends on B, so when the construction method of the B object changes, the A object must also be changed

When the construction method in B is changed, A of newB must also be changed, otherwise an error will be reported

243c4063ee0f43b88075d6ab454b0506.png

2664776773ec43daa76d52371dba0f0e.png

after change

af9d27b6c38d44db96b621d342f75298.png

 NewA's Test also needs to be changed

6c00c76796864da68dbaae51db3eda9e.png

 1c37dca797364bedb296761ee8668dff.png

It can be found that when the bottom layer changes, the entire call chain needs to change

This reflects the problem of a relatively high degree of coupling between codes. How to solve it?

We write a decoupled way of writing

cd7a6dce9e5a4c9499f8bb293b2550ca.png

c507ef5a77e84fc894273820cadb433f.png

0d673308bae24720a65a36311f2009b1.png

6961167172ab49df82077b855686c98d.png

831666105aef4cdd8f8372864f0a7960.png

At this point we change the constructor of B

9e77b063d2c34f18ba4a1fa33435ebfb.png

The first few classes will not report an error, but the test class that provides it reports an error

e5c16bd8b06947869e0295683f462528.png

fbc0d7945e014abe8d6e928d22d01bca.png

This approach achieves decoupling

Traditional way: Test depends on A, A depends on B

Decoupling method: B passes into A, A passes into Test

is a reverse process

The life cycle of these classes is not controlled by dependent classes

Summarize:

Solution: Decoupling, when using objects, do not actively new objects, and switch to external acquisition

Even if the parameters of the lower class are changed, the current class itself does not need to be changed, which is the decoupling of the program

IoC is responsible for the creation of objects and initialization of a series of tasks. The created or managed objects are collectively referred to as Beans in the IoC container.

The core idea of ​​IoC: the control of object creation is transferred from the program to the outside. This idea is called inversion of control.

A only uses the B object, does not perform the new object operation, just uses. Who creates the B object A does not care

At this point, the A object has no control over the B object. The control is handed over, which is the inversion of control!

Back to the theme of Spring, it is an IoC container that contains many method tools, that is, Spring provides an IoC container to act as the "external" in IoC thinking, it has the right to create and destroy objects, and it has storage Objects and Capabilities to Get Objects

Core functions: store objects into containers, and take objects out of containers

What are the benefits of using Spring to access objects?

Putting the object in the container is equivalent to making all the tools that may be used in the future and putting them in the warehouse. When needed, take them out and use them, and put them back into the warehouse when they are used up. The new object method will be recycled when it is empty after use. To use Have to re-new.

There is also a concept that needs to be mentioned, Dependency Injection, or DI for short, means dependency injection

Dependency injection: During the running of the IoC container, a certain dependency is dynamically injected into the object.

It can be seen that IoC is a guiding ideology, and DI is its specific implementation.

2. Spring creation and use

Create Spring

Creating a Spring project is divided into three steps

1. Create a normal Maven project

2. Add Spring framework support

3. Add startup class

1. Create a normal Maven project

2311e0d947574751bb5235af59610a90.png

This means that the project has been initialized

deafcf8830184bcabbc39ce10661901a.png

2. Add Spring dependency

It is necessary to configure the domestic source, otherwise the download will be very slow

8b1ed909a5fe42ccacf8de9ed02a246c.png

Need to use the support of the major version number 5 and jdk to match 

43cafd5364b5400fb62120a2c83fc6a6.png

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.26</version>
</dependency>

then click refresh

0ccc2332b8e5413195487c86ca654f17.png Add dependency successfully

7d96b6c924f8473db6cbabad8a477ea1.png

3. Create a startup class

8239a5633ddd4ea8b199560906ed9e73.png

Next we store the Bean object in Spring

access bean

1. Create Bean

Bean: If it is used many times in Java, it is called Bean

090231e3449545f3a6875216ecdda1c3.png

2. Store the Bean in the Spring container

Configure Bean information through Spring's configuration file 

dd8b4821139f4c89a79ebb6bbc2e75f1.png

e5a11bec756b4734a2095d08dff632a4.png

3. Get Bean from Spring

 Get the Spring (context) object first, using ClassPathXmlApplicationContext

ba81ab7b39674ce89091460d9e146a82.png

 The ClassPathXmlApplicationContext class implements the ApplicationContext interface

eebb7e86aae34c4d975fd788dd87501a.png

ClassPathXmlApplicationContext belongs to the subclass of ApplicationContext, has all the functions of ApplicationContext, and obtains all bean containers through xml configuration

Note that the path in "" must be written correctly, corresponding to the .xml file under resourses, otherwise the bean we set cannot be found

Then you can get the bean

fe27ed714a91431ab064901217740a1d.png

82c63474b3e64941bb4e34555cdee40d.png

The content of this parameter must be the same as the id configured in .xml to get the bean

e85be45238f645d89d1446c4b8318e06.png

 result:

3c69c8c7a3b0414796e19f231ecbb5e5.png

Get the bean object and use it without new object

There are two other ways to get it:

cb4b19bfa9e7409ebcf3025ff43c9f9d.png

06350590aa5743518b19a7e3ee2eab34.png

83ea9e78b1d04c77a44eb90a7c7c85dd.png

This process is DI implemented through code, which dynamically injects dependencies into objects!

 BeanFactory can also get the context of Spring

It can be seen that Application Context is also a subtype of it, which is an extension of its function

public class Application2 {
    public static void main(String[] args) {
        //1.得到spring上下文对象
        BeanFactory beanFactory =
                //不推荐使用,是因为早期时内存珍贵,现在内存价格低廉.
                //特征:省内存,调用时加载初始化bean到spring容器,效率不高!
                new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
        //2.从容器中获取对象

        //第一种获取方式:这个写法是有问题的,如果本身是"null",强转会出错

        Student s2 = (Student) beanFactory.getBean("student");
        //3.使用对象
        s2.sayHi();
    }
}

 e4c3fb0f50b94940b0ae3bb5d42cf347.png

The difference between BeanFactory and ApplicationContext

So what is the difference between these two methods?

Let's create another class

842fa65396ac4c3687b411afb032bdd9.png

Configure Bean information

25e47754fd904488b717ec17cbfd7fdf.png

 We just call this line of code that gets the context

bef6dba3f6e440c4a79e5f81909a0254.png we can find out that:

ApplicationContext is one-time loading, which consumes more memory, but subsequent reading is very fast, and all beans in spring will be initialized and all instantiated into spring!! Hungry man mode

Beanfactory does not, it uses lazy loading, and only when the get bean is executed will the corresponding bean be loaded!!!

In terms of inheritance relationship:

910279f864cf4fd0af8063bae6bf8d4f.png

Spring has two top-level interfaces, BeanFactory and ApplicationContext. BeanFactory provides basic access to containers, and ApplicationContext is a subclass of BeanFactory. In addition to inheriting BeanFactory, it also has other features, adding support for internationalization, resources Access support, and support for event propagation, etc.

3. Summary

1. Create a Spring project

Create a Maven project

Add Spring-context dependency

Create a startup class

2. Storage Bean

Create a Bean object

Through the Spring configuration file (spring-config.xml)

<bean id="bean name" class="package name + class name"></bean>

 3. Read Bean

Get the Spring context (BeanFactory and ApplicationContext)

Get the Bean object through the Spring object.getBean() method (this process is DI)

use beans

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/chenchenchencl/article/details/130122083