[Spring] Project creation and use

 Hello, hello, everyone~ I am your old friend: protect Xiao Zhou ღ  


Speaking of frameworks in the Java circle, the oldest and most dazzling one is the Spring framework, which has become one of the most popular and widely used Java development frameworks. I don't know if you have thought about these issues when using the Spring framework. What is a framework? What is Spring? How to understand Spring? What is loC and DI, and what is the difference? What is the core function of Spring? This article will explain it to everyone, let’s take a look~


This issue is included in the blogger's column : JavaEE_Protect Xiao Zhouღ's Blog-CSDN Blog

Suitable for programming beginners, interested friends can subscribe to view other "JavaEE Basics".

Stay tuned for more highlights: Protect Xiaozhou ღ *★,°*:.☆( ̄▽ ̄)/$:*.°★*'


1. The concept of Spring

The book continues from the previous chapter, Spring: An IoC container that contains many tools and methods.

The core of Spring: IoC (Inversion of Control), DI (Dependency Injection).

loC (Inversion of Control) translated into Chinese means "inversion of control". Inversion of control is a kind of programming design idea , which changes the control flow of the program from the traditional active calling method to the passive receiving method (the inside of a class is no longer Instead of instantiating another class, it tells the program that this class needs to use that class as a parameter to run), so as to achieve decoupling and dependency management between objects.

DI (abbreviation for Dependency Injection - "Dependency Injection") "Dependency Injection" refers to the dynamic injection of certain dependencies into objects by the IoC container during runtime (during program execution). The traditional approach is for the program to actively find and instantiate the objects it depends on, while DI is for the container to actively inject dependencies into the objects. The advantage of this is decoupling between objects.
Since Spring is an loC container, it has two basic functions:

  • Storing the object into the container (Spring)
  • Get the object out of the container (Spring)

An ordinary instantiated object in Java is also called a Bean object , and the objects we encounter in the framework are called Bean objects.

Friends who want to know more about Spring concepts can read another blog of the blogger:

[Spring] Core and Design Ideas_Protecting Xiao Zhouღ's Blog-CSDN Blog


2. Create a Spring project

After we understand what Spring is, we will demonstrate how to create a Spring project in combination with IDEA (Integrated Development Environment).

2.1 Create a normal Maven project (no need to use templates)

When you come to this interface, it means that the creation is


2.2 Add Spring framework support

Spring is an open source Java framework created in 2002 by Rod Johnson. Spring provides many features that simplify Java development, so it is widely used and recognized in the Java development community. Spring is a third-party resource (framework) that encapsulates and expands existing functions, making it easier for programmers to write functions. It does not belong to the official JDK, so we need to download third-party dependencies if we want to use Spring.

You only need to add support for the Spring framework to the pom.xml document in the project, and the xml configuration is as follows

<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>

As can be seen from the above configuration, the added framework includes spring-context: spring context, and spring-beans: module for managing objects. The specific role is described below.


1.3 Add a startup class

Finally, create a startup class under the Java folder of the created project, including the main method:

public class App {
    public static void main(String[] args) {

    }
}

In this startup class, we can perform a series of operations on the Bean object.


3. Store objects in Spring

To store Bean objects (objects after class instantiation) requires 2 steps:

  • Create a bean object - requires a class
  • Register the bean object in Spring [use the Spring configuration file to register]

3.1 Creating Bean Objects

The so-called Bean object is an ordinary object in Java.

public class Dog {
    // 狗的属性
    private String name;
    private int age;
    private String sex;
    private String color;


    // 狗的行为
    public void cry() {
        System.out.println(this.name + "汪汪~");
    }

    /**
     * 小狗的做我介绍
     * @return
     */
    @Override
    public String toString() {
        return "Dog{" +
                "我叫做:'" + name + '\'' +
                ", 我今年:" + age +
                "岁, 我的性别是:" + sex +
                ", 我是'" + color + '\'' + "的" +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

Conventional practice:

public class App {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.setName("哈巴狗");
        dog.setAge(3);
        dog.setSex("公");
        dog.setColor("白色");
        dog.cry();
        System.out.println(dog.toString());
    }
}


3.2 Register the Bean object with Spring 

Here is an old registration method - [Registration using Spring configuration files]

Add the Spring configuration file spring-test.xml to the created project , and put the file in the root directory of resources :

  The name of the configuration file spring-test.xml can be any name, but the file suffix must be (.xml) , and the file name here will be used in the subsequent fetching of the Bean object.

This file is a Spring configuration file, and the format is also fixed (no need to remember, just find a document and save it):

<?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>

Next, just realize how to register our custom object (Dog) in Spring, and the specific operation is added in the <beans> tag.

<beans xmlns="http://www.springframework.org/schema/beans"
    <bean id="dog" class="Dog"></bean>
</beans>

​If you need to register multiple bean objects in Spring, just repeat the above operations. Note: Each bean object needs to be aliased (identified).


Fourth, get and use the Bean object from Spring 

Obtaining and using the Bean object is divided into three steps:

  • Get the Spring context object (this object maintains all bean objects), because the objects are handed over to Spring management, so to get objects from Spring, you need to get the Spring context first.
  • Through the context of Spring, get a specified Bean object (by the identity set when storing the bean object)
  • The return value is an instance of the Bean object, so we can use it directly.

If you need to take out multiple Bean objects, repeat steps 2 and 3 above

4.1 Create a Spring context object

The context of Spring refers to the data structure that stores Bean objects in the Spring container , and can also be understood as the environment in the Spring container.

Currently the Spring context object can be obtained using the ApplicationContext interface:

The ApplicationContext in the Spring framework is an IoC container responsible for managing the Bean objects in the application. It is a configuration file that provides the configuration information required by the Bean objects and is also a container for the Bean objects. Through ApplicationContext, developers can store Bean objects in the container and use these Bean objects in other components.

//1. 获取 Spring 上下文对象,创建的时候需要配置 Spring 的配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("spring-test.xml");

 


In addition to using ApplicationContext, we can also use the BeanFactory interface to obtain the Spring context.

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

The main function of BeanFactory is to manage the life cycle of Bean, including operations such as Bean creation, destruction and dependency injection. BeanFactory is the basic interface of the IoC container in the Spring framework, which provides registration and acquisition of Bean objects.

Regardless of whether you use ApplicationContext or BeanFactory to get the Spring context, the effect of the two is the same. But they are different in the way.

The same points of ApplicationContext VS BeanFactory
:

  1. You can get the Spring context object
  2. Both are top-level interfaces of the Spring container (both can manage bean objects)

difference:

  1. In terms of inheritance relationship and function: ApplicationContext belongs to the subclass of BeanFactory, BeanFactory only has the most basic ability to manage bean objects, and ApplicationContext inherits BeanFactory and naturally has its basic functions. In addition, it also expands more Functions, such as: internationalization support, resource access support, and event propagation support.
  2. From a performance point of view: the way to load the Spring context object obtained by ApplicationContext is to instantiate all the bean objects in the Spring container in memory at one time after startup, so it is very fast to obtain the Bean object later; BeanFactory The way to load the obtained Spring context object is to load (instantiate) the Bean object when a Bean object is needed, so it will be slower when obtaining the Bean object.

In the historical version of the Spring framework, the ApplicationContext interface has existed since the Spring 2.x version, but the BeanFactory is still a core interface and has not been eliminated.

Until the Spring 3.1 version, the official has begun to recommend the use of the ApplicationContext interface instead of the BeanFactory for Bean management and instantiation. The reason is that ApplicationContext adds more functions on the basis of BeanFactory, such as internationalization, event publishing, AOP introduction, web environment support, etc., which can better meet the needs of development.

ClassPathXmlApplicationContext belongs to the subclass of ApplicationContext, has all the functions of ApplicationContext, and is a container for obtaining all Bean objects through the configuration of xml files (files storing Bean objects).


4.2 Get the specified Bean object

In the previous step, we obtained the context object of Spring, which is used to manage Bean objects. If we need to obtain a specific Bean object, we need to call the getBean() method on the basis of the context object

The getBean() method is the core method for obtaining Bean instances from the Spring container.

The function currently introduced to you is to read the Bean object:

Obtain the specified bean definition from the Spring container through the bean ID or bean name, and throw an exception if it is not found.

//1. 获取 Spring 上下文对象,创建的时候需要配置 Spring 的配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("spring-test.xml");
        
//2. 从 Spring 上下文中取出某个 bean 对象
Dog dog = (Dog)context.getBean("dog");// dog是我们给 Dog 类的实例取得的标志(名字)

Precautions:

Otherwise it will throw: NoSuchBeanDefinitionException exception


4.2.1 Use of getBean() method

The getBean() method has many overloaded methods, and we can also use other methods to obtain Bean objects.

1. Obtain according to the id (flag) of the bean object [already mentioned above]

// dog是我们给 Dog 类的实例取得的标志(名字)
Dog dog = (Dog)context.getBean("dog");

Use the id of the bean object to get it, the Spring context object—the return value of context is Object, so a forced type conversion is required.  

2. Get the bean according to the type 

Dog dog = context.getBean(Dog.class);

Because we directly use the type of the bean object to get it, we don't need to manually force the type conversion, and it will be automatically forced when getting it.

3.  Get the bean according to the id (flag) + type of the bean object

 Dog dog = context.getBean("dog",Dog.class);

The difference of the second method from the first method is that:

When a class is repeatedly registered in the configuration file of spring-test.xml, it can only be obtained by ID (name).

At this point, two instances of the Dog class (bean objects) are stored in the Spring container.

We use the type to get the bean object and use it:

Therefore, when the same type of object is registered in Spring multiple times, the program will report an error. At this time, we should use the ID (name) of the bean object to obtain it. But the disadvantage of this method is that we need to manually perform type conversion (the return type is Object)

So we recommend using the third method : get the bean object according to the bean object's id (flag) + type. 


4.3 Using Bean Objects

As mentioned above, the Bean object is actually an ordinary instantiated object, and the Bean object is just a name. So the use of Bean objects is no different from the use of our traditional objects:

public class App {
    public static void main(String[] args) {
        //1. 获取 Spring 上下文对象,创建的时候需要配置 Spring 的配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-test.xml");

        //2. 使用类型从 Spring 容器中获取 bean 对象
        Dog dog = context.getBean("dog",Dog.class);

        //3. bean 对象的使用
        dog.setName("哈巴狗");
        dog.setAge(3);
        dog.setSex("公");
        dog.setColor("白色");
        dog.cry();
        System.out.println(dog.toString());  
    }
}


V. Summary

1. Spring is an loC (Inversion of Control) container containing many tools and methods, which belongs to a third-party library, so when we use Spring, we need to inject relevant dependencies into the project. Since it is a container, it has two basic functions, storage and take out.

2. Store Bean objects

  • Create a Bean object (that is, an instantiated object of a common class)
  • Register (configure) the Bean object to: Spring configuration file [.xml file]

 

The file name is user-defined, but try to keep it standard, and the configuration file name is required when extracting the Bean object from Spring. How to inject, please see the above analysis...

3. Get the Bean object

  • There are two ways to obtain the Spring context object (managing the Bean object): ApplicationContext interface (official recommendation), Beanfactory (old version)
  • Get an object from the context object and call the getBean() method. There are three ways to get this method, according to the ID (identification) of the bean object , and according to the type of the Bean object. Disadvantages: the first requires mandatory type conversion, and the second The program will report an error when there are Bean objects of the same type. Therefore, it is recommended to use the third method: get according to the Bean object ID and object type
  • After obtaining the Bean object, it can be used normally, which is the same as our regular usage

The operation process is shown in the figure below:


Well, here, [Spring] project creation and use  bloggers have finished sharing, I hope it will be helpful to everyone, if there is anything wrong, welcome to criticize and correct. 

The next preview: use annotations to use Spring more simply 

Store Bean objects in Spring more simply: use annotations [class annotations/method annotations]

Thank you to everyone who read this article, and more exciting events are coming: Protect Xiaozhou ღ *★,°*:.☆( ̄▽ ̄)/$:*.°★* 

When I met you, all the stars fell on my head ...

Guess you like

Origin blog.csdn.net/weixin_67603503/article/details/131353398