Several ways to create beans

1. Create the bean object through the reflection call constructor

The most commonly used method is to call the constructor of the class to get the corresponding bean instance. This method simply specifies the class attribute in the XML bean element, and the spring container automatically calls the constructor of that type to create the bean object and place it in the container for use.

<bean id="Bean name" name="Bean name or alias" class="Full type name of bean">
    <constructor-arg index="0" value="The value of the bean" ref="Referenced bean name" />
    <constructor-arg index="1" value="The value of the bean" ref="Referenced bean name" />
    <constructor-arg index="2" value="The value of the bean" ref="Referenced bean name"/ >... <constructor-arg index="n" value="The value of the bean" ref="Referenced bean name" />
</bean>
Copy the code
  • Constructor-arg is used to specify the values of constructor parameters
  • Index: The position of the arguments in the constructor, ascending from 0
  • Value: Specifies the value of a parameter
  • Ref: When the value inserted is another bean in the container, this value is the name of the corresponding bean in the container
2. Create the bean object using the static factory method

We can create static factories, internally provide static methods to generate the objects we need, and give the objects created by these static methods to Spring for use.

<bean id="Bean name" name="" class="Static Factory Full class name" factory-method="Static Factory approach">
    <constructor-arg index="0" value="The value of the bean" ref="Referenced bean name" />
    <constructor-arg index="1" value="The value of the bean" ref="Referenced bean name" />
    <constructor-arg index="2" value="The value of the bean" ref="Referenced bean name"/ >... <constructor-arg index="n" value="The value of the bean" ref="Referenced bean name" />
</bean>
<bean id="Bean name" name="" class="Static Factory Full class name" factory-method="Static Factory approach">
    <property name="name" value=""/>
    <property name="age" value=""/>
</bean>
Copy the code
  • Class: Specifies the full class name of the static factory
  • Factory-method: A static method in a static factory that returns the desired object.
  • Constructor-arg is used to specify the values of static method parameters in the same way as the constructor method described above
3. Create the bean object using the instance factory method

Have the Spring container call some instance methods of some object to generate bean objects for use in the container.

<bean id="Bean name" factory-bean="Name of instance object bean to call" factory-method="Methods in bean objects">
    <constructor-arg index="0" value="The value of the bean" ref="Referenced bean name" />
    <constructor-arg index="1" value="The value of the bean" ref="Referenced bean name" />
    <constructor-arg index="2" value="The value of the bean" ref="Referenced bean name"/ >... <constructor-arg index="n" value="The value of the bean" ref="Referenced bean name" />
</bean>
Copy the code

The Spring container looks up the bean object with the factory-bean value for the bean name, then calls the method specified by the factory-method property value in that object, and places the object returned by this method in the container for use as the current bean object

4. Create bean objects using FactoryBean
public class UserFactoryBean implements FactoryBean<UserModel> {
    int count = 1;
    @Nullable
    @Override
    public UserModel getObject(a) throws Exception { / / @ 1
        UserModel userModel = new UserModel();
        userModel.setName("I'm the first one created by FactoryBean."+count+++ "Object");/ / @ 4
        return userModel;
    }
    @Nullable
    @Override
    publicClass<? > getObjectType() {return UserModel.class; / / @ 2
    }
    @Override
    public boolean isSingleton(a) { 
        return true; / / @ 3}}Copy the code

Bean label

Property paraphrase
class The fully qualified name of the class
name Can specify id, name(separated by comma, semicolon, space)
scope scope
constructor arguments Specify construction parameters
properties Sets the value of the property
autowiring mode No (default), byName, byType, constructor
lazy-initialization mode Lazy loading (not lazy loading if it is dependent on a non-lazy loaded bean)
initialization method This method is called after the bean properties have been set
destruction method Callback method after bean destruction

The scope of the Bean

When defining a bean in Spring, you must declare the bean’s scoped options. The Spring framework supports the following five scopes: Singleton, PropToType, Request, Session, and Global Session.

scope describe
singleton There is only one example Bean in the Spring IOC container, and the Bean exists as a singleton, default
prototype Each time the Bean is called from the container, a new instance is returned, that is, each time getBean() is called, the equivalent of executing new XXBean()
request Each HTTP request creates a new Bean, which is scoped only for the webApplicationContext environment
session Each HTTP session request creates a new bean. Different sessions use different beans, only for WebApplicationContext
Global – session (application) Generally used in protlet applications. This application domain applies only to WebApplicationContext

Signleton scope

Singleton is the default scope, that is, when defining a Bean, the scope of the Bean is default to Signleton if no scope configuration item is specified.

When a bean is scoped to a Singleton, there is only one shared bean instance in the Spring IOC container, and all requests for the bean, as long as the ID matches the bean definition, are grayed back to the same instance of the bean.

That is, when a Bean definition is set to the Singleton scope, the SpringIOC container creates only a unique instance of that Bean definition.

Singleton is a singleton pattern that automatically creates a Bean object when you create the container. Whether you use it or not, it exists, and the object you get is the same object each time. Note that the Singleton scope is the default scope in Spring.

ProtoType scope:

When a Bean is scoped to Propertype, a Bean definition corresponds to multiple object instances. The protoType scope causes a new Bean instance to be created each time a request is made to the Bean.

Prototype is the primitive type that wasn’t instantiated when we created the container. Instead, we create an object when we get the Bean, and we don’t get the same object each time.

Request scope:

When the scope of a bean is Request, it indicates that one bean corresponds to one instance in an HTTP request. A bean instance is created for each HTTP request, and the bean ends when the request ends. The Request scope is used in the Spring container’s Web environment.

Session scope:

This is similar to request, which is also used in the Web environment. Beans are shared at the session level. Each session corresponds to one bean instance, and different sessions correspond to different bean instances.

Application scope:

The global Web application level effect, also used in the Web environment, is one bean instance for each Web application, which is generally similar to singleton’s effect, except that singleton has only one bean instance per Spring container. The application has only one Spring container. However, multiple Spring containers can be created in an application. However, the application only has one bean with the same name, no matter how many Spring containers there are in the application.

Injection pattern

public class User {
    
    private String name;
    
    private int age;
    public String getName(a) {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge(a) {
        return age;
    }
    public void setAge(int age) {
        this.age = age; }}public class Food {
    
    private String name;
    private double price;
    private User user;
    
    public String getName(a) {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice(a) {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public User getUser(a) {
        return user;
    }
    public void setUser(User user) {
        this.user = user; }}Copy the code

Constructor injection

  • 1. Inject according to constructor parameter index
<bean id="user" class="xxx.User">
  <constructor-arg index="0" value="Zhang"/>
  <constructor-arg index="1" vlue="19" / > < / bean >Copy the code

Constructor-arg The user specifies the constructor argument index: the position of the constructor argument, starting from 0 value: Constructor parameter values, the value can be used to give a simple type set values, the value corresponding to the attribute type can only as a byte, int, long, float, double, Boolean, byte, long, float, double, enumeration, The spring container converts the value of value to the corresponding type during internal injection.

  • Injection based on the constructor parameter type
<bean id="user" class="xxx.User">
  <constructor-arg type="String" value="zhangsan"/>
  <constructor-arg type="int" value="20"/>
</bean>
Copy the code

Constructor – arg user to specify a constructor parameter type: complete types of constructor parameters, such as: Java. Lang. String, int, double value: the value of the constructor parameters, simple value can only be used to set the type of value

  • 3. Inject by constructor parameter name
<bean id="user" class="xxx.User">
  <constructor-arg name="String" value="zhangsan"/>
  <constructor-arg name="int" value="20"/>
</bean>
Copy the code

Constructor-arg The user specifies the constructor parameter name: the constructor parameter name value: the constructor parameter value. Value can only be used to set values for simple types

Set method injection

• get/set methods

<bean id="user" class="xxxx.User">
  <property name="name" value="xxx"/>
  <property name="age"  value="13"/> 
</bean>
<bean id="food" class="xxxx.Food">
  <property name="name" value="branana"/>
  <property name="price" value="1.3"/>
  <property name="user" ref="user"/>
</bean>
Copy the code

• Instance factory injection

<! The Spring container needs to create a SimpleFactory object before it can call the factory method"factory" class="cn.tewuyiang.factory.SimpleFactory"/ > <! Create three beans using the factory method of the instance factory, specify the factory object with factory-bean and specify the factory method to call with factory-method --> <bean id="name" factory-bean="factory" factory-method="getName" />
<bean id="age" factory-bean="factory" factory-method="getAge" />
<bean id="car" factory-bean="factory" factory-method="getCar" />
<bean id="user" class="cn.tewuyiang.pojo.User"> <! Inject the bean created by the instance factory method above into the user --> <property name="name" ref="name"/>
    <property name="age" ref="age"/>
    <property name="car" ref="car"/>
</bean>
Copy the code

• Annotation injection

@Autowired@Resource@Value
Copy the code