Spring bean definition and property assignment


Spring Bean

Objects managed by the Spring IoC container are called beans, and beans are created based on information in the Spring configuration file

The Spring IoC container can be regarded as a large factory, and the Bean is equivalent to the product of the factory. If you want this big factory to produce and manage beans, you need to tell the container which beans are needed and how to assemble them.

Spring configuration files support two formats, the XML file format and the Properties file format.

The Properties configuration file mainly exists in the form of key-value key-value pairs, which can only be assigned values ​​and cannot perform other operations. It is suitable for simple property configuration.
The XML configuration file adopts a tree structure with a clear structure and is more flexible than the Properties file. But XML configuration is cumbersome and suitable for large and complex projects.

Normally, Spring's configuration files are in XML format. The root element of an XML configuration file is that this element contains multiple child elements. Each element defines a bean and describes how the bean is assembled into the Spring container.

A simple Spring bean

Entity class User
This is a simple entity class

public class User {
    
    
    private Integer age;
    private String name;
    public void setAge(Integer age) {
    
    
        this.age = age;
    }
    public void setName(String name) {
    
    
        this.name = name;
    }
    @Override
    public String toString() {
    
    
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

Register the User bean in spring.xml, hand it over to spring management
, define the bean in spring's xml configuration file, and write the full class of the User class, so that the spring factory can use the reflection mechanism to create objects, and then configure Attribute name, and value value, provided that the User class provides corresponding setter methods for these fields, so that spring can use the reflection mechanism to call the setter methods to complete dependency injection, perfect

<!-- User -->
<bean class="com.liu.c.User" id="user">
    <property name="age" value="18"/>
    <property name="name" value="小刘"/>
</bean>

Test
Create a startup factory, get the user object, and print

public class TestUser {
    
    
    public static void main(String[] args) {
    
    
        String springProperties = "spring.xml";
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(springProperties);
        User user = context.getBean("user", User.class);
        System.out.println(user);
    }
}

result

Because the spring factory defaults to the singleton mode, the singleton will instantiate the object when the factory is created, and use the Java reflection mechanism for dependency injection, so we see that the rewrite is called by default when printing the user 's toString method, and successfully assigns the property

User{age=18, name='小刘'}

Of course, if you want the spring factory to create multiple instances of objects, you only need to add them to the corresponding bean configuration, scope属性and the configuration scope="prototype"can implement multiple instances. The default singletonmeans a single instance.

 <!-- User -->
<bean class="com.liu.c.User" id="user" scope="prototype">
    <property name="age" value="18"/>
    <property name="name" value="小刘"/>
</bean>
public class TestUser {
    
    
    public static void main(String[] args) {
    
    
        String springProperties = "spring.xml";
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(springProperties);
        User user = context.getBean("user", User.class);
        User user1 = context.getBean("user", User.class);
        System.out.println(user.hashCode());
        System.out.println(user1.hashCode());
    }
}

Are you right, Paige?
insert image description here

33317023
13818597

Two ways of Spring Bean property injection

Spring mainly uses two ways to inject properties

  • setter injection (important)
  • Construct injection (understand know)

setter injection

In the process of Spring instantiating a bean, the IoC container will first call the default constructor (no parameter constructor) to instantiate the bean (Java object), and then call the setXxx() method of the bean through the Java reflection mechanism to set the attribute value. Inject into Bean

Step:
Provide a default no-argument constructor in the bean, because if there is no no-argument construction, spring cannot create an object by means of no-argument construction, let alone obtain the setter method in the object through reflection and assign it (no other In the case of a constructor with parameters, it can be omitted, and the default is to construct with or without parameters), and provide a property for all properties that need to be injected. setXxx() 方法
In Spring's XML configuration file, use <beans>and its sub-elements <bean>to define the bean and use
within the <bean>element <property>Elements assign values ​​to various properties.

The User above the specific code is assigned through the setter, so I won't write it redundantly here. For other types of injection, it will be written in the next article. Friends who need it can pay attention to me, and you can communicate together. ! Let's talk about injecting using the constructor method

Constructor injection

We can implement Bean's property injection through the Bean's parameterized constructor.

Steps
Add a parameterized constructor to the Bean, and each parameter in the constructor represents a property that needs to be injected;
in Spring's XML configuration file <beans>, <bean>define the Bean through and its sub-elements; use
the <bean>element <constructor-arg>the element to Attributes in the constructor are assigned, and as many parameters as there are in the constructor of the bean, the number of <constructor-arg>elements .

Retrofit User

User
provides a parameterized structure, and the default parameterless structure will be overwritten, so the parameterless structure can be defined again

public class User {
    
    
    private Integer age;
    private String name;

    public User() {
    
    
    }

    public User(Integer age, String name) {
    
    
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

spring.xml uses construction to assign values

<!-- User -->
<bean class="com.liu.c.User" id="user" scope="prototype">
    <constructor-arg name="age" value="15"/>
    <constructor-arg name="name" value="小张"/>
    <!--这里也可以使用index,就是说构造方法的参数,注意是从0开始的哦,那这里的0就表示user构造函数的
    第一个参数age,以此类推,但不建议这样使用,因为可读性变差了,养成好习惯,关注代码的可维护-->
<!--        <constructor-arg index="0" value="15"/>-->
<!--        <constructor-arg index="1" value="小张"/>-->
</bean>

The result is
successfully assigned, why is it not recommended? For example, for example, there are many attributes in this class, and then you need to rewrite many construction methods, which will be very bloated and troublesome.

User{age=15, name='小张'}

Well, that's all for today. I'll share the injection method for other types of injections, such as arrays and collections tomorrow. It's also very simple. After learning about injection, let's learn about the scope and life cycle of beans, OK , bye ヾ(•ω•`)o

insert image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324321697&siteId=291194637