Bean management refers to spring’s two operations: creating objects and injecting properties.

Creating objects has been done in previous articles, so this injection property is easy to understand. For example, the class has a property private String userName; If I want to set a value for this property, the class can provide a set() method that I can call. This process, now managed by Spring, is called injecting properties.

Spring has two approaches to Bean management: xmL-based configuration file, annotation-based, and in this case xmL-based configuration file.

Create an object

1). Create the bean tag in the configuration file.



2). There are two attributes:

  • Id: This refers to the alias name of the object by which the object can be obtained.
  • Class: The full path of the class of the object to be created, as shown in the figure"com.pingguo.spring5.User".

3). When creating an object, the default no-argument constructor is executed.

Injection properties

Also known as DI, dependency injection. This needs to be done on the basis of creating the object.

1). Use the set method to inject

With the set method, you can now inject the values of attributes into the XML configuration file via the property tag:

  • Name: Attribute name of the class
  • Value: indicates the value to be injected

To test the effect, I add a testBook() method to the Book class, print out the value of the injected bookName, and call it in the test function.

Running results:

2). Construct injection with arguments

I directly modified the previous example code to define the class attributes and the corresponding parameter constructors, which can be injected into the configuration file. Use the constructor-arg tag:

  • Name: Attribute name of the class
  • Value: indicates the value to be injected

Run the test code again and check that the results are correct.

3). Inject null value

To inject a null value into familiarity, write:

Results after running:

4). Inject special symbols

If I want to inject a value with a special symbol, such as << Test note that bit the apple into tears >>, USE
: