Instantiation of Spring beans

There are three types of Bean instantiation in Spring

  1. Constructor instantiation
  2. Static factory instantiation
  3. Instantiate the chemical plant mode

Create an entity class Person1

public class Person1 {
    
    private String name;
    private int age;
    private String sex;

    public Person1(int age, String sex) {
        this.age = age;
        this.sex = sex;
    }

    public Person1(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person1(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public Person1(a) {
        System.out.println("I'm a no-parameter constructor.");
    }

    @Override
    public String toString(a) {
        return "Person1{" +
                "name='" + name + '\' ' +
                ", age=" + age +
                ", sex='" + sex + '\' ' +
                '} ';
    }
Copy the code

Constructor instantiation

Instantiate the Bean configuration file using the class’s default constructor (no parameter constructor) :


      
<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="person" class="com.lyl.testBean.Person1"/>

</beans>
Copy the code

The test class:

 public static void main(String[] args) {
        // Initialize the Spring container and load the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext1.xml");

        System.out.println(context.getBean("person");
    }
Copy the code

Print result:

com.lyl.testBean.Person1@50f8360d
Copy the code

This should be the most straightforward and simplest instantiation of beans (in Spring).


Parameter constructor configuration file:


      
<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="person" class="com.lyl.testBean.Person1">
      <constructor-arg index="0" name="name" type="java.lang.String" value="Zhang"/>
      <constructor-arg index="1" name="age" type="int" value="6"/>
   </bean>

   <bean id="person2" class="com.lyl.testBean.Person1">
      <constructor-arg index="1" name="sex" type="java.lang.String" value="Daisy"/>
      <constructor-arg index="0" name="age" type="int" value="18"/>
   </bean>

   <bean id="person3" class="com.lyl.testBean.Person1">
         <constructor-arg index="0" name="name" type="java.lang.String" value="Bill"/>
         <constructor-arg index="1" name="age" type="int" value="18"/>
         <constructor-arg index="2" name="sex" type="java.lang.String" value="Male"/>
   </bean>

   <bean id="person4" class="com.lyl.testBean.Person1">
         <constructor-arg index="0" name="name" type="java.lang.String" value="6"/>
         <constructor-arg index="1" name="age" type="int" value="16"/>
   </bean>

</beans>
Copy the code

The test class:

 public static void main(String[] args) {
        // Initialize the Spring container and load the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext1.xml");

         System.out.println(context.getBean("person"));
        System.out.println(context.getBean("person2"));
        System.out.println(context.getBean("person3"));
        System.out.println(context.getBean("person4"));
    }
Copy the code

Print result:

Person1{name='null', age=6, sex='null'} Person1{name='null', age=18, sex=' 0 '} Person1{name=' 0 ', age=18, sex=' 0 '} Sex =' male '} Person1{name='6', age=16, sex='null'}Copy the code


Constructor has several parameters has several index this tag attributes: commonly known as the Angle of mark, the order of the parameters, from 0 (the first constructor to form parameter name attribute: commonly known as the parameter name, parameters of the parameter name, this property to have and to preserve the index and the corresponding constructor parameter name, if not the same, may be an error! Type property: data type, need to write fully qualified class name! Value: an argument. The value must be the same as the data type in the corresponding type. Otherwise, an error will be reported.

Static factory instantiation

Create a static factory class:

// Static factory class
public class MyStaticBeanFactory {
    // Create a factory method for Bean instantiation
    public static Person1 createPerson1(a){
        return newPerson1(); }}Copy the code

Configuration file:


      
<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">
   <! Class refers to the fully qualified class name of the static factory class, and factory-method refers to the createPerson1() method of the static factory class to get the Bean instance.
   <bean id="person" class="com.lyl.testBean.MyStaticBeanFactory" factory-method="createPerson1"/>

</beans>
Copy the code

The test class:

 public static void main(String[] args) {
        // Initialize the Spring container and load the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
       
        System.out.println(context.getBean("person"));
    }
Copy the code

Print result:

com.lyl.testBean.Person1@174d20a
Copy the code

Defines a Bean with id person, class specifies the fully qualified class name of the static factory class, and factory-method is the bean-bearing instance that informs the Spring container to invoke the createPerson1() method of the static factory class.

It may seem a little hard to understand, but it’s essentially calling the createPerson1() method of the static factory, and what is the Bean? A Bean is a Java class after all. Spring simply calls a method in the process. If there is a return value, it will pass the return value to the Bean. An error!

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'person' defined in class path resource [applicationContext2.xml]: Invalid factory method 'createPerson1': needs to have a non-void return type! "Main" thread org. Springframework. Beans. Factory. The abnormal bencreationException: Error creating bean named "person" defined in classpath resource [applicationContext2.xml] : Invalid factory method "createPerson1" : Need to have non-empty return type!Copy the code

You can see that Spring does not allow no return value, which means the method must have a return value! The modifier cannot be void.

Instantiate the chemical plant mode

Create instance chemical factory class:

public class MyBeanFactory {
    MyBeanFactory(){
        System.out.println("Person1 factory instantiation...");
    }
    
    public Person1 createPerson1(a){
        return newPerson1(); }}Copy the code

Configuration file:


      
<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="myFactory" class="com.lyl.testBean.MyBeanFactory"/>
   
   <bean id="person" factory-bean="myFactory" factory-method="createPerson1"/>

</beans>
Copy the code

The test class:

  public static void main(String[] args) {
        // Initialize the Spring container and load the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext3.xml");

        System.out.println(context.getBean("person"));
    }
Copy the code

Print result:

Person1 factory instantiation... com.lyl.testBean.Person1@174d20aCopy the code

This seems a little more complicated than the static factory class instantiating beans, so let’s take a look at this separately.

First look at the example chemical plant class:

We know that an object that wants Person1 from the factory class can only call createPerson1(), which is not static, so we need an instance of the factory class to call the method. OK! So we know that to get an object of the Person1 class, we need to create an object of the instance chemical class.

Take a look at the configuration file:

Class specifies the fully qualified class name of the instance chemical factory class. Isn’t it a bit like the constructor instantiating beans?

The Bean with id person has two more attributes (factory-bean, factory-method) and no more common class attributes.

So the test class:

In the configuration file, the Bean named Person does not have the fully qualified class name specified by class. Instead, it has the factory-bean property.

Factory-bean — factory (As the name implies, factory-bean is the factory object that generates the bean. The factory-bean attribute is used together with the factory-method attribute, first creating the factory class and method that generates the bean.)

So how did you end up with the Person1 class object? Tell Spring to load the Bean with id person, check for factory-bean and factory-method properties, and find the Bean with id myFactory and initialize it according to the class property. Call the factory class using the method of the value in the factory-method property and pass the return value. This is how I understand a Bean to be instantiated by an instance chemical class. My understanding is definitely not completely correct, but at least it can help us understand the surface operation process in the early stage, and then we must apply it to the actual project to practice and summarize.

Note:

Q: When creating a Bean with the Spring container, is the object created before or when the getBean(” XXX “) method is called? A: When ApplicationContext loads the configuration file, the Spring container automatically creates the Bean in the configuration file and saves it. The getBean() method actually gets the object in the Spring container. This problem can be found when using constructors to create objects, such as when a no-parameter constructor prints “I am a no-parameter constructor, I am created!” Instead of writing the getBean() method in the test class, just load the configuration file, and the console prints out the output statement of the no-argument constructor, proving that the Bean object is created when the configuration file is loaded, not when the getBean method is called. A: Setter injection is more general and flexible depending on the business situation. A: Setter injection is more convenient, but it also has the disadvantages that the class must have A corresponding constructor. If not, objects cannot be created through this method.