The difference between JavaBean and SpringBean and the way to create SpringBean

  • 2021-11-24 01:41:48
  • OfStack

Directory 1: Object, JavaBean, SpringBean Difference 1. What is JavaBean2. What is SpringBean3. SpringBean and JAVABean Difference 2: How to define an SpringBean1. Through ClassPathXmlApplicationContext2. Through AnnotationConfigApplicationContext Bottom 3. Through BeanDefinition4. Through FactoryBean5. Through Supplier

1: Difference between object, JavaBean and SpringBean

1. What is JavaBean

javaBean requires all attributes to be private, the class must have a public parameterless constructor, and private attributes must provide public Getter setter for external access


/**
 * @author yzh
 * @date 2021/4/29 8:42
 **/
public class User {
    //javaBean All properties are required to be private , This class must have 1 Common parameterless constructors ,private Property must provide a public Getter setter Give external access 
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

2. What is SpringBean

SpringBean is an object managed by Spring, and all objects managed by Spring can be SpringBean

3. Differences between SpringBean and JAVABean

Different uses: Traditional javabean passes parameters more as values, while bean in spring is almost ubiquitous, and any component can be called bean Different writing: traditional javabean as a value object requires each attribute to provide getter and setter methods; However, bean in spring only needs to provide setter methods for properties that accept set injection

Life cycle is different: traditional javabean is passed as a value object and does not accept any container to manage its life cycle; bean in spring has spring managing its lifecycle behavior

2: How to define an SpringBean

Preparation: Introducing Spring dependency package


<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.14.RELEASE</version>
</dependency>

1. Through ClassPathXmlApplicationContext

configLocation needs to be specified through ClassPathXmlApplicationContext, so we now create a new Spring. xml file under resources directory


<?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.2.xsd">
    <!--  Assemble instances using set-value injection  -->
    <bean id="user1" class="org.example.bean.User">
        <property name="name" value="zhangsan" />
    </bean>
    <!--  Assemble instances using constructors  -->
    <!-- Assembling using constructors requires providing constructors in the corresponding classes -->
    <bean id="user2" class="org.example.bean.User">
        <constructor-arg index="0" value="lisi" />
    </bean>
</beans>

At the same time, the toString method is rewritten for the corresponding object, which is convenient for better observation of user1 and user2


package org.example.bean;
/**
 * @author yzh
 * @date 2021/4/29 8:42
 **/
public class User {
    //javaBean All properties are required to be private , This class must have 1 Common parameterless constructors ,private Property must provide a public Getter setter Give external access 
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public User(String name) {
        this.name = name;
    }
    public User() {
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

Run the test class


package org.example.bean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * @author yzh
 * @date 2021/4/29 8:45
 **/
public class Main {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext();
        classPathXmlApplicationContext.setConfigLocation("Spring.xml");
        classPathXmlApplicationContext.refresh();
        User user1 = classPathXmlApplicationContext.getBean("user1",User.class);
        System.out.println(user1);
        User user2 = classPathXmlApplicationContext.getBean("user2", User.class);
        System.out.println(user2);
    }
}

The results are as follows

User{name='zhangsan'}

User{name='lisi'}

2. Through the AnnotationConfigApplicationContext bottom layer

It is also implemented through BeanDefinition

* @ Bean @ Component @ Service @ Controller will do; 1 @ Service is used for Service layer, @ Controller is used for Controller layer, and @ Bean is used as an example here

Create a new Config class and label User @ Bean


package org.example.bean;
import org.springframework.context.annotation.Bean;
/**
 * @author yzh
 * @date 2021/4/29 9:20
 **/
public class Config {
    @Bean
    public User user(){
        return  new User();
    }
}

Get bean through AnnotationConfigApplicationContext and print bean object


package org.example.bean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * @author yzh
 * @date 2021/4/29 8:45
 **/
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(Config.class);
        annotationConfigApplicationContext.refresh();
        User user = annotationConfigApplicationContext.getBean("user",User.class);
        System.out.println(user);
    }
}

Running result

User{name='null'}

3. Through BeanDefinition


package org.example.bean;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * @author yzh
 * @date 2021/4/29 8:45
 **/
public class Main {
    public static void main(String[] args) {
  
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
 
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        // Definition 1 A Bean
        beanDefinition.setBeanClass(User.class);
        // Put the generated Bean Register in a container 
        annotationConfigApplicationContext.refresh();
        annotationConfigApplicationContext.registerBeanDefinition("userTest",beanDefinition);
        User userTest = annotationConfigApplicationContext.getBean("userTest", User.class);
        System.out.println(userTest);
    }
}

Running result

User{name='null'}

4. Through FactoryBean

4.1 Through FactoryBean and annotation

First, create a new Person class


package org.example.bean;
import org.springframework.stereotype.Component;
/**
 * @author yzh
 * @date 2021/4/29 10:00
 **/
public class Person {
}

Then create a new PersonFactoryBean class, implement the FactoryBean interface, override its methods, and annotate it with @ component, which is the same effect as annotating it on Person class


package org.example.bean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;
/**
 * @author yzh
 * @date 2021/4/29 10:01
 **/
@Component("person")
public class PersonFactoryBean implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        return new Person();
    }
    @Override
    public Class<?> getObjectType() {
        return Person.class;
    }
}

Next, add an Config class with @ ComponentScan ("org. example. bean") to scan the comments under the package


<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.14.RELEASE</version>
</dependency>
0

Finally, Bean is obtained by AnnotationConfigApplicationContext


<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.14.RELEASE</version>
</dependency>
1

Running result

org.example.bean.Person@28ac3dc3

4.2 Through Factory and BeanDefinition

1. Create a new Person class as in 4.11

2. Create a new PersonFactoryBean class as in 4.11 to implement the FactoryBean interface, but without annotation

3. Object retrieval via BeanDefinition

The difference between this and annotation generation is that registration through BeanDefinition will generate two Bean objects, one of which is person corresponding to Person, and the other is Person & The corresponding type of person is PersonFactoryBean, as can be seen from the getBean method of the following code! !


<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.14.RELEASE</version>
</dependency>
2

The results are as follows

org.example.bean.PersonFactoryBean@3aeaafa6

org.example.bean.Person@76a3e297

Note

The FactoryBean interface provides three methods, but we override two because the other one is implemented by default

The FactoryBean interface method is as follows:


package org.springframework.beans.factory;
import org.springframework.lang.Nullable;
public interface FactoryBean<T> {
    
    String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";
    @Nullable
    T getObject() throws Exception;
    
    @Nullable
    Class<?> getObjectType();
    // Default implementation method , Whether it is a singleton 
    default boolean isSingleton() {
        return true;
    }
}

5. Through Supplier


<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.14.RELEASE</version>
</dependency>
4

bean injection mode This article only provides a variety of api, in many cases, the bottom actually uses a kind of things, only provides a different way of use, the specific can be viewed through the source code.


Related articles: