Getting to Know the Spring Container

First, the definition and core functions of Spring

definition:
Spring 是包含了众多工具方法的 loC 容器

Core functions:

  • Import objects into the Spring container
  • Get objects from the Spring container

1.1 loC container

容器We all know the definition of用来容纳某些物品的装置

IoCSo what is it?

IoC (Inversion of Control) That is “控制反转”, to sum up, Spring is a container for "inversion of control"

As we all know, Java is object-oriented. In the face of a relatively complex system, we will decompose the system into objects one by one. These object classes are encapsulated and implemented internally. They are transparent to the outside world and can be flexibly reused. be extended to make problem solving easier.

IoC 理论就是借助于第三方实现具有依赖关系的对象之间的解耦

For example, the two objects A and B are interdependent, and A depends on B.

  • If there is no IoC container, when implementing the A object, when the B object is needed, it will actively create a B object (new B()) or use the already created B object, but in either case, A Subject has absolute control
  • If the IoC container is introduced, when the B object is needed in the process of implementing the A object, the IoC container will actively create a B object and inject it into the A object, and A can directly take the ready-made B object, and the object A becomes Become the passive party, the control is reversed, that is, "inversion of control"

It can be seen that when the IoC container is introduced, the A object does not need to consider the B object at all 两者之间没有了耦合关系. The object A only needs to implement its own functions. If you want to use the B object, you can directly use the injected object B directly. Put it back in the IoC container when you're done. And the method of new object B is equivalent to what you want, make one on the spot, throw it away when you run out, and make another on the spot if you want it next time.

1.2 DI

When talking about the IoC container above, I mentioned a word called "injection"

DI(Dependency Injection) Immediately“依赖注入”

From a macro perspective, DI and IoC mean the same thing, but they are different in detail. The two actually illustrate the same thing from two different perspectives.

Thinking, since IoC is Inversion of Control, what exactly is being inverted?

Based on the section above on IoC, it's not hard to know, 获取依赖对象的过程被反转too. After being reversed, the process of obtaining dependent objects has changed from self-creation and management to IoC container directly injecting dependent objects and taking ready-made ones. Therefore, "inversion of control" has a new name "dependency injection", the so-called "dependency injection", that is 由 IoC 容器在运行期间,动态地将某种依赖关系注入到对象中.

IoCis a 思想kind of guiding principle

DI the realization of ideas具体方法

通过引入了 IoC 容器这样的一个思想,具体用依赖注入(DI)的方式,实现对象之间的解耦

For example, if I want to connect my computer to the network (thought), whether it is to connect to the campus network, or to share it directly with the mobile phone hotspot, this is the specific implementation.

Second, the creation and use of Spring

2.1 Create a Spring project

Step 1: Create a normal Maven project

File -> New -> Project

insert image description here

Maven -> Next

insert image description here

fill 项目名称in and项目存储路径

insert image description here

Step 2: Add Spring dependencies

Add Spring framework support in pom.xml (this is a fixed piece of code, just paste and copy)

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
</dependencies>

After adding dependencies, you need to click the Maven 点击刷新button in the upper right corner to refresh

insert image description here

Introduced dependencies include spring -content , ie Spring 的上下文, get the Spring container through this. Also spring-beans, a bean refers to an object, and the dependency is管理对象的模块

Step 3: Add a startup class

Create a startup class in the java folder, the startup class is a class that contains the main method

insert image description here

2.2 Storing Bean Objects

Beanmeans in Java对象

Step 1: Create a Simple Bean Object

insert image description here

Step 2: Register the created Bean object in the Spring container

Add the configuration file spring.xml under the resource (the name of the file can be created by yourself), the initial code is fixed, just paste and copy

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
</beans>

insert image description here

Then, formally register the previously created Bean object (BeanDemo) with Spring

<beans>
    <bean id="beanOne" class="com.beans.BeanDemo"></bean>
</beans>

insert image description here

Going back to get the BeanDemo object, you can pass the id of beanOne. The class written in the class is where the BeanDemo object is located.包名加类名

2.3 Get and use Bean objects

Step 1: Get the Spring context object

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

The parameters passed in when creating should correspond to the previous configuration file name

Step 2: Get a specified Bean object

BeanDemo beanDemo = (BeanDemo) context.getBean("beanOne");

insert image description here

Step 3: Using the Bean Object

beanDemo.func();

2.4 Program Results

At this point, a simple Spring creation and use code is completed, just click the green triangle in the main method to run

insert image description here
insert image description here

2.5 Supplement

2.5.1 Difference between ApplicationContext and BeanFactory

In addition to using ApplicationContext, you can also use the context object to obtainBeanFactory

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring.xml"));

You can also getBean() through the beanfactory variable, the usage is similar to ApplicationContext, and the effect is the same

The difference between the two:

  1. Since 继承关系, ApplicationContext is a subclass of BeanFactory
  2. From the point of view 功能方面, BeanFactory provides the basic ability to access the container. As its subclass, ApplicationContext not only inherits all the functions of BeanFactory, but also adds support for internationalization, resource access, and event propagation.
  3. From the point of view 性能方面, ApplicationContext loads and initializes all Bean objects at one time (initialization is slow, invocation is fast), and BeanFactory needs which bean will be loaded, which is more lightweight (initialization is fast, invocation is slow)

insert image description here

2.5.2 More usage of getBean method

The usage of the getBean method in the above example is to directly pass in the id of the Bean to be used, but it 缺点is需要进行类型强制转换

There are two more common usages

Pass in the class object of the desired Bean:

BeanDemo beanDemo = context.getBean(BeanDemo.class);

The advantage is that the Bean object is obtained according to the type, and no type casting is required.

缺点That is, when the BeanDemo class is 重复注册added to spring.xml, it will程序异常

insert image description here

Pass in the id and type of the desired bean:

BeanDemo beanDemo = context.getBean("beanOne",BeanDemo.class);

This method is used more frequently. By passing in the id and type, it is not necessary to cast the type, but also avoid the exception caused by the multiple registration of the type.

2.6 Summary

insert image description here

Finish!

Guess you like

Origin blog.csdn.net/weixin_46103589/article/details/124460421