3 IoC operation - Factory bean, scope of bean, life cycle of bean

1. Factory bean

There are two types of bean s in Spring:

  • Ordinary bean: the type of bean defined in the configuration file is the return type.
  • Factory bean: the bean defined in the configuration file can be different from the returned type.

The following is an example to understand a factory Bean:
Step 1: create a class, use this class as a factory bean, and implement the interface FactoryBean;
Step 2: implement the method in the interface and define the returned bean type in the implemented method.

Create a class:

package com.atguigu.spring5.factorybean;

import com.atguigu.spring5.Book;
import org.springframework.beans.factory.FactoryBean;

//Because the Object type is returned by default, we add the writing method of a generic class to make its return type Book
public class MyBean implements FactoryBean<Book> {

    @Override
    public Book getObject() throws Exception {   //Return bean instance
        Book book = new Book();
        book.setBname("A Town Besieged");
        book.setBauthor("Qian Zhongshu");
        return book;
    }

    @Override
    public Class<?> getObjectType() {     //Return bean type
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

Configure in the configuration file:

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

    <bean id="myBean" class="com.atguigu.spring5.factorybean.MyBean"></bean>

</beans>

Test:

    @Test
    public void testDemo1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean5.xml");
        Book book = (Book)applicationContext.getBean("myBean",Book.class);
        book.testdemo();
    }

Program execution results:

2. Scope of bean

  • In Spring, we can set whether the created bean instance is single instance or multi instance.
  • In Spring, by default, the bean created is a single instance object.
  • How to set whether the created bean is single instance or multi instance?
    In the bean tag of the spring configuration file, there is a property (scope) to set single instance or multiple instances. The values of the scope property are:
    • Singleton, the default value, represents a single instance object. When the scope value is set to singleton, a single instance object will be created when the spring configuration file is loaded.
    • Prototype, which represents a multi instance object. When the scope value is set to prototype, the instance object is not created when the spring configuration file is loaded, but the multi instance object is created when the getBean() method is called.
    • request
    • session

3. bean life cycle

3.1 life cycle

Life cycle refers to the process from object creation to object destruction.

3.2 bean life cycle:

  1. Create bean instance through constructor (no parameter construction);
  2. Set values for bean properties and references to other beans (call the set method);
  3. Call the initialization method of the bean (we need to configure the initialization method);
  4. The bean can be used (the object is obtained);
  5. When the container is closed, call the bean destruction method (we need to configure the destruction method).

3.3 life cycle of demo bean

Create a class:

package com.atguigu.spring5.bean1;

public class Orders {
    //Nonparametric construction
    public Orders(){
        System.out.println("Step 1: execute parameterless construction creation bean example");
    }

    private String oname;

    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("Step 2: call set Method to set the property value");
    }

    //Step 3: create an initialization method for execution (it needs to be configured in the configuration file so that the initialization method will be executed by default)
    public void initMethod(){
        System.out.println("Step 3: create an initialization method for execution");
    }

    //Step 5: create the destruction method to be executed (it needs to be configured in the configuration file to make it execute automatically)
    //This method is executed only when the bean is destroyed
    public void destroyMethod(){
        System.out.println("Step 5: execute the destruction method");
    }
}

Configure in the configuration file:

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

    <bean id="orders" class="com.atguigu.spring5.bean1.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="Jerry"></property>
    </bean>

</beans>

Test:

@Test
    public void testBean4(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean6.xml");
        Orders orders = (Orders)applicationContext.getBean("orders");
        System.out.println("Step 4: get the created bean Instance object");
        System.out.println(orders);

        //Manually destroy the bean instance
        ((ClassPathXmlApplicationContext)applicationContext).close();
    }

Program execution results:

3.4 post processor of bean

Plus the post processor of the bean, the life cycle of the bean has a total of 7 steps:

  1. Create bean instance through constructor (no parameter construction);
  2. Set values for bean properties and references to other beans (call the set method);
  3. The method of passing the bean instance to the bean post processor (postProcessBeforeInitialization);
  4. Call the initialization method of the bean (we need to configure the initialization method);
  5. The method of passing the bean instance to the bean post processor (postProcessAfterInitialization);
  6. The bean can be used (the object is obtained);
  7. When the container is closed, call the bean destruction method (we need to configure the destruction method).

3.5 demonstrate the effect of adding a post processor

First, create a class to implement the interface (BeanPostProcessor) and create a post processor.
Because we want to implement this interface, we need to implement the methods in this interface. (move the cursor to the imported BeanPostProcessor, and then ctrl+h to view the methods of the interface.)

package com.atguigu.spring5.bean1;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.lang.Nullable;

public class MyBeanPost implements BeanPostProcessor {
    @Override
    // Step 3: pass the bean instance to the bean post processor before calling the bean initialization method
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("Method executed before initialization");
        return bean;
    }

    // Step 5: after calling the bean initialization method, pass the bean instance to the bean post processor method
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("Method executed after initialization");
        return bean;
    }
}

Configure the post processor in the configuration file:

    <!-- Configure post-processing. If it is written in this way, it will be used for all in the current configuration file bean All instances are added with post processors -->
    <bean id="myBeanPost" class="com.atguigu.spring5.bean1.MyBeanPost"></bean>

Program execution result after adding post processor:

Tags: Java Spring

Posted on Tue, 21 Sep 2021 00:52:22 -0400 by cravin4candy