[Spring framework] I finally understand ApplicationContext (detailed explanation of the case)

Keywords: Java Spring Back-end

[Chen Xi should work hard]: hello, I'm Chen Xi. I'm glad you can read it. The nickname is that I hope I can constantly improve and move forward towards excellent programmers!

The blog comes from the summary of problems encountered in the project and programming. Occasionally, there will be reading and sharing. I will continue to update the summary of relevant knowledge points such as Java front-end, background, database and project cases. Thank you for your reading and attention. I hope my blog can help more people share and obtain new knowledge and make progress together!

We quarryers should have the heart of a cathedral. May everyone rush to their own love

1, Basic concepts

This issue focuses on sharing the basic concepts and application scenarios of ApplicationContext

The most basic interface of Spring container is BeanFactory. Bean factory is responsible for configuring, creating and managing beans;

ApplicationContext is derived from BeanFactory; Many functions of BeanFactory need to be implemented by programming, and can be implemented by configuration in ApplicationContext;

ApplicationContext is also called Spring context. The Spring container is responsible for managing the dependencies between beans.

2, Case study

This synchronization will review the knowledge of Spring scope singleton + prototype

Go directly to the case to see what ApplicationContext can help us do?

Create a user object

@Data
public class User {
    private String id;
    private String name;
    private Integer age;
}

Create a configuration file of applicationContext.xml

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

    <!--    singleton-->
    <bean id="UserSingleton" class="com.chenxi.demo.po.User" scope="singleton">
        <property name="id" value="1"/>
        <property name="name" value="Chen Xi"/>
        <property name="age" value="22"/>
    </bean>

    <!--    prototype-->
    <bean id="UserPrototype" class="com.chenxi.demo.po.User" scope="prototype" >
        <property name="id" value="2"/>
        <property name="name" value="Chen Xi should work hard"/>
        <property name="age" value="23"/>
    </bean>

</beans>

Create a test class to help us learn ApplicationContext

import com.chenxi.demo.po.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @program: ApplicationContextDemo
 * @description: ApplicationContext Introductory learning
 * @author: Chen Xi should work hard
 * @create: 2021-11-10 22:07:54
 */
public class ApplicationContextDemo {

    //Print log
    private static final Logger logger = LoggerFactory.getLogger(ApplicationContextDemo.class);

    public static void main(String[] args) {
        /**
         *
         * ApplicationContext Architecture
         * Main implementation classes:
         * ClassPathXmlApplicationContext: Load the configuration file from the classpath by default
         * FileSystemXmlApplicationContext: Mount configuration files from the file system by default
         */
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        /**
         * Singleton: Single instance (it has been created and saved in the container before the container is started, and the object created before is obtained at any time)
         */
        User user = (User) applicationContext.getBean("UserSingleton");
        User user1 = (User) applicationContext.getBean("UserSingleton");
        /**
         * Another way to write it: < T > t getBean (string VAR1, class < T > var2) throws beanexception;
         */
        User user2 =  applicationContext.getBean("UserSingleton",User.class);

        logger.info("user.hashCode()yes:{}",user.hashCode());
        logger.info("user1.hashCode()yes:{}",user1.hashCode());

        logger.info("user yes:{}",user);
        logger.info("user1 yes:{}",user1);
        logger.info("user == user1 :{}",user == user1);



        /**
         * Prototype: Multi instance (by default, multi instance bean objects will not be created when the container is started, but only when it is acquired, and a new instance object will be created every time it is acquired)
         */
        User user3 = (User) applicationContext.getBean("UserPrototype");
        User user4 = (User) applicationContext.getBean("UserPrototype");

        logger.info("user3.hashCode()yes:{}",user3.hashCode());
        logger.info("user4.hashCode()yes:{}",user4.hashCode());
        logger.info("user3 yes:{}",user3);
        logger.info("user4 yes:{}",user4);
        logger.info("user3 == user4 :{}",user3 == user4);

    }
}

Execution code: console log

22:00:32.921 [main] INFO com.chenxi.demo.utils.ApplicationContextDemo - user.hashCode()yes:1446002
22:00:32.922 [main] INFO com.chenxi.demo.utils.ApplicationContextDemo - user1.hashCode()yes:1446002
22:00:32.922 [main] INFO com.chenxi.demo.utils.ApplicationContextDemo - user yes:User(id=1, name=Chen Xi, age=22)
22:00:32.922 [main] INFO com.chenxi.demo.utils.ApplicationContextDemo - user1 yes:User(id=1, name=Chen Xi, age=22)
22:00:32.922 [main] INFO com.chenxi.demo.utils.ApplicationContextDemo - user == user1 :true
22:00:32.923 [main] INFO com.chenxi.demo.utils.ApplicationContextDemo - user3.hashCode()yes:266875004
22:00:32.923 [main] INFO com.chenxi.demo.utils.ApplicationContextDemo - user4.hashCode()yes:266875004
22:00:32.923 [main] INFO com.chenxi.demo.utils.ApplicationContextDemo - user3 yes:User(id=2, name=Chen Xi should work hard, age=23)
22:00:32.923 [main] INFO com.chenxi.demo.utils.ApplicationContextDemo - user4 yes:User(id=2, name=Chen Xi should work hard, age=23)
22:00:32.923 [main] INFO com.chenxi.demo.utils.ApplicationContextDemo - user3 == user4 :false

Code logic

Create a factory class for Spring

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

Get Bean instance by parsing XML through factory

User user = (User) applicationContext.getBean("UserSingleton");

Expansion supplement

1. If the objects are equal, the hashcodes must be equal;
2. hashCode objects are not necessarily equal

The above is why I compare the two objects with = =, which is just enough to review the knowledge points related to spring scope

ApplicationContext summary

If BeanFactory is the heart of Spring, then ApplicationContext is a complete body.

ApplicationContext is derived from BeanFactory and provides more application-oriented functions.


Context is usually interpreted as context. It is easier to understand it by using "container", and ApplicationContext is "application container"

Thank you very much for reading here. If this article is helpful to you, I hope to leave your praise 👍 follow ❤️ share 👥 Leaving a message. 💬 thanks!!!

November 10, 2021 22:16:39 may you go in your love!

Posted by DGaleDavid on Wed, 10 Nov 2021 11:40:21 -0800