Spring learning notes: instantiation of Bean

catalog:

🥪 1, Instantiated Bean

🍬 1.1 environmental preparation

🍬 1.2 instantiation of construction method (common)

🍕 Step 1: prepare the class to be created

🍕 Step 2: configure the class to the Spring container

🍕 Step 3: write the running program

🍕 Step 4: provide constructor test in class

🍕 Step 5: change the constructor to private test

🍕 Step 6: add a parameter test to the constructor

🍬 1.3 static factory instantiation (understand)

🍕 1.3.1 creating bean s in factory mode

🍕 1.3.2 static factory instantiation

  🍕 1.3.3 thinking:

🍬 1.4 example factory (understand)

🍕 1.4.1 environmental preparation

🍕 1.4.2 instance factory instantiation (understand)

🍬 1.5. Use of FactoryBean (practical and must be mastered)

  🍕 1.5.1 thinking 1: is the object we created a singleton or a non singleton?

🍕 1.5.2 thinking 2: how to turn a single case into a non single case?

🍬 1.6 Bean instantiation summary

🍕 (1) How are bean s created?

🍕 (2) Spring's IOC instantiates objects in the following three ways:?

🥪 1, Instantiation of Bean

There are three ways to instantiate bean s: construction method, static factory and instance factory

A bean is essentially an object. When an object is new, it will be completed using the construction method, and the creation of a bean is also completed using the construction method.

🍬 1.1 environmental preparation

(1) Create a Maven project

(2)pom.xml add dependency

(3) Add the spring configuration file ApplicationContext. Under resources xml

 

🍬 1.2 instantiation of construction method (common)

🍕 Step 1: prepare the class to be created

Prepare a BookDao and BookDaoImpl class

public interface BookDao {
    public void save();
}
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("book dao save ...");
    }

}

🍕 Step 2: configure the class to the Spring container

<?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="bookDao" class="com.system.dao.impl.BookDaoImpl"/>

</beans>

🍕 Step 3: write the running program

public class AppForInstanceBook {
    public static void main(String[] args) {
        ApplicationContext ctx = new 
            ClassPathXmlApplicationContext("applicationContext.xml");
        BookDao bookDao = (BookDao) ctx.getBean("bookDao");
        bookDao.save();

    }
}

🍕 Step 4: provide constructor test in class

Add a parameterless constructor to the BookDaoImpl class and print a sentence to facilitate observation of the results.

public class BookDaoImpl implements BookDao {
    public BookDaoImpl() {
        System.out.println("book dao constructor is running ....");
    }
    public void save() {
        System.out.println("book dao save ...");
    }

}

Run the program. If the console prints the output in the constructor, it indicates that the Spring container also uses the constructor when creating objects

🍕 Step 5: change the constructor to private test

public class BookDaoImpl implements BookDao {
    private BookDaoImpl() {
        System.out.println("book dao constructor is running ....");
    }
    public void save() {
        System.out.println("book dao save ...");
    }

}

Run the program and it can be executed successfully. It shows that the internal constructor is still used and the private construction methods in the class can be accessed. It is obvious that the underlying layer of Spring uses reflection

🍕 Step 6: add a parameter test to the constructor

public class BookDaoImpl implements BookDao {
    private BookDaoImpl(int i) {
        System.out.println("book dao constructor is running ....");
    }
    public void save() {
        System.out.println("book dao save ...");
    }

}

The underlying program is constructed by using the Spring method, which will run without error.

🍬 1.3 static factory instantiation (understand)

Spring's second bean creation method: static factory instantiation. This method is generally used to be compatible with some early old systems. You can understand it

🍕 1.3.1 creating bean s in factory mode

(1) First, create an OrderDao and OrderDaoImpl class

public interface OrderDao {
    public void save();
}
public class OrderDaoImpl implements OrderDao {
    public void save() {
        System.out.println("Factory created object successfully");
    }
}

(2) Create a factory class OrderDaoFactory and provide a static method

//Static factory creation object
public class OrderDaoFactory {
    public static OrderDao getOrderDao(){
        return new OrderDaoImpl();
    }
}

(3) Write AppForInstanceOrder to run the class and get the object through the factory in the class

public class AppForInstanceOrder {
    public static void main(String[] args) {
        //Creating objects through static factories
        OrderDao orderDao = OrderDaoFactory.getOrderDao();
        orderDao.save();
    }
}

(4) After running, you can view the results:

🍕 1.3.2 static factory instantiation

(1) In the spring configuration file application Add the following to properties:

<bean id="orderDao" class="com.system.factory.OrderDaoFactory" factory-method="getOrderDao"/>

Class: full name of factory class

Factory method: the method name of the object created in the concrete factory class

(2) Run the class in AppForInstanceOrder and use the method to get the bean from the IOC container to run the test

public class AppForInstanceOrder {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        OrderDao orderDao = (OrderDao) ctx.getBean("orderDao");
        orderDao.save();

    }
}

(3) After running, you can view the results

  🍕 1.3.3 thinking:

This method is not also a direct new object in the factory class. It is not much different from my direct new. Moreover, the static factory method is more complex. What is the significance of this method?

Because in the static method of the factory, we can do other business operations in addition to the new object. If you follow the previous new object method, you cannot add other business content. For example:

public class OrderDaoFactory {
    public static OrderDao getOrderDao(){
        System.out.println("Factory configuration");
        return new OrderDaoImpl();
    }
}

Rerun to see the results

 

🍬 1.4 example factory (understand)

Spring's third bean creation method: instance factory instantiation

🍕 1.4.1 environmental preparation

(1) Prepare a UserDao and UserDaoImpl class

public interface UserDao {
    public void save();
}
public class UserDaoImpl implements UserDao {

    public void save() {
        System.out.println("Instance factory created object successfully ...");
    }
}

(2) Create a factory class UserDaoFactory and provide a common method. Note that this is different from the factory class of a static factory in that the method is not a static method

public class UserDaoFactory {
    public UserDao getUserDao(){
        return new UserDaoImpl();
    }
}

(3) Write the AppForInstanceUser run class and get the object through the factory in the class

public class AppForInstanceUser {
    public static void main(String[] args) {
        //Create instance factory object
        UserDaoFactory userDaoFactory = new UserDaoFactory();
        //Create objects from instance factory objects
        UserDao userDao = userDaoFactory.getUserDao();
        userDao.save();
}

(4) After running, you can view the results

🍕 1.4.2 instance factory instantiation (understand)

The specific implementation steps are as follows:

(1) Add the following to the spring configuration file:

<bean id="userFactory" class="com.system.factory.UserDaoFactory"/>
    <bean id="userDao" factory-method="getUserDao" factory-bean="userFactory"/>

The operation sequence of the example chemical plant is:

① Create an instance factory object, corresponding to the first line of configuration

② Call the method in the object to create the bean, which corresponds to the second line of configuration

Factory bean: instance object of the factory

Factory method: the method name of the concrete creation object in the factory object

Factory method: the method name of the object created in the concrete factory class

(2) In the AppForInstanceUser run class, use the method to get the bean from the IOC container to run the test

public class AppForInstanceUser {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) ctx.getBean("userDao");
        userDao.save();
    }
}

(3) After running, view the results

<bean id="userFactory" class="com.system.factory.UserDaoFactory"/>

<bean id="userDao" factory-method="getUserDao" factory-bean="userFactory"/>

You need to configure an instance factory bean first, which is the userFactory in the first line.

Next, use factory bean to point to factory bean. The bean in the first line is only for use. In fact, it has no meaning. It's just for making it for use.

The problem with factory method is that the method name is not fixed and needs to be reconfigured every time.

spring makes an improvement to fix a method when writing the factory method method without creating a useless bean. This improvement method is FactoryBean

🍬 1.5. Use of FactoryBean (practical and must be mastered)

The specific steps are as follows:

(1) Create a UserDaoFactoryBean class, implement the FactoryBean interface, and rewrite the methods of the interface

public class UserDaoFactoryBean implements FactoryBean<UserDao> {
    //Replace the method of creating objects in the original instance factory
    public UserDao getObject() throws Exception {
        return new UserDaoImpl();
    }
    //Returns the Class object of the created Class
    public Class<?> getObjectType() {
        return UserDao.class;
    }
}

(2) Configure in the Spring configuration file

 <bean id="userDao" class="com.system.factory.UserDaoFactoryBean"/>

(3) The appforinstanceuser run class runs directly without any modification

  🍕 1.5.1 thinking 1: is the object we created a singleton or a non singleton?

We can recompile it in the AppForInstanceUser file

public class AppForInstanceUser {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao1 = (UserDao) ctx.getBean("userDao");
        UserDao userDao2 = (UserDao) ctx.getBean("userDao");
        System.out.println(userDao1);
        System.out.println(userDao2);
    }
}

Run it to see if the result is single or non single

Obviously, this object is a singleton

🍕 1.5.2 thinking 2: how to turn a single case into a non single case?

Generate a {isSingleton() method in the UserDaoFactoryBean file, and modify it to return false, that is, it becomes a non singleton. If true is written, it is a single example.

public class UserDaoFactoryBean implements FactoryBean<UserDao> {
    // Replace the method of creating objects in the original instance factory
    public UserDao getObject() throws Exception {
        return new UserDaoImpl();
    }

    //Returns the Class object of the created Class
    public Class<?> getObjectType() {
        return UserDao.class;
    }
    //Set singleton and non singleton
    public boolean isSingleton() {
        return false;
    }
}

Rerun AppForInstanceUser to view the results

From the results, we can see that the is already a non singleton, but generally, the default is a singleton, so the isSingleton() method generally does not need to be written.

🍬 1.6 Bean instantiation summary

🍕 (1) How are bean s created?

Construction method

🍕 (2) Spring's IOC instantiates objects in the following three ways:?

① Construction method (common)

② Static factory (understand)

③ Example factory (understand)

④ FactoryBean (Practical)

Focus on mastering the construction method and FactoryBean

It should be noted that the constructor will be provided by default in the class, but if the constructor is rewritten, the default will disappear. In the process of use, it should be noted that if the constructor needs to be rewritten, it is best to rewrite the default constructor.

Tags: Java Spring Back-end programming language

Posted by timc37 on Sun, 15 May 2022 01:17:37 +0300