002SpringIOC002 configuring beans based on XML files

1 manage ordinary beans

1.1 creating objects

The creation of objects can be realized by using bean tags in the configuration file.

The configuration is as follows:

1 <bean id="user" class="com.demo.spring.User"></bean>

By default, the parameterless constructor in the class is used.

Attribute description in bean tag:

id attribute: represents the unique identification of the object.

Class attribute: the full path of the class where the created object is located.

name attribute: similar to id attribute, special symbols can be used, but less used. It is an attribute used earlier.

1.2 injection properties

1.2.1 inject attributes through setter method

In this way, you need to use the property tag, provide parameterless construction methods, and define properties and their setter methods.

The configuration is as follows:

1 <bean id="user" class="com.demo.spring.User">
2     <property name="name" value="Zhang San"></property>
3     <property name="age" value="22"></property>
4 </bean>

Property description in the property tag:

Name attribute: the attribute name of the object.

Value attribute: the attribute value of the object.

1.2.2 injecting attributes through constructors

This method needs to use the constructor Arg tag, provide parameter construction methods, and define properties, but does not require setter methods.

The configuration is as follows:

1 <bean id="user" class="com.demo.spring.User">
2     <constructor-arg name="name" value="Zhang San"></constructor-arg>
3     <constructor-arg name="age" value="22"></constructor-arg>
4 </bean>

Attribute description in constructor Arg tag:

Name attribute: the attribute name of the object.

Value attribute: the attribute value of the object.

Type attribute: the type corresponding to the attribute of the object; can be omitted. If it is a basic type, write the basic type; if it is a reference type, write the full class name.

index attribute: inject attributes according to the order of attributes in the constructor, which is rarely used. The order of properties in the constructor starts at 0.

1.2.3 injecting attributes through namespaces

You can use p namespaces to set properties, but less often.

This method requires the use of p attributes, parameter free construction methods, and the definition of attributes and their setter methods.

Need to add p namespace:

1 <beans xmlns="http://www.springframework.org/schema/beans"
2        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3        xmlns:p="http://www.springframework.org/schema/p"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

The configuration is as follows:

1 <bean id="user" class="com.demo.spring.User" p:name="Zhang San" p:age="22"></bean>

1.3 injection of special attributes

1.3.1 inject Null value

The configuration is as follows:

1 <bean id="user" class="com.demo.spring.User">
2     <property name="name">
3         <null />
4     </property>
5 </bean>

1.3.2 inject values containing special symbols

The configuration is as follows:

1 <bean id="user" class="com.demo.spring.User">
2     <property name="name">
3         <value><![CDATA[Zhang San]]></value>
4     </property>
5 </bean>

1.4 inject other Bean objects

1.4.1 inject external beans

You can inject other Bean objects by injecting external beans.

The configuration is as follows:

1 <bean id="sz" class="com.demo.spring.Address">
2     <property name="province" value="Guangdong Province"></property>
3     <property name="city" value="Shenzhen City"></property>
4 </bean>
5 <bean id="user" class="com.demo.spring.User">
6     <property name="name" value="Zhang San"></property>
7     <property name="address" ref="sz"></property>
8 </bean>

Property description in the property tag:

ref attribute: the id attribute of the external Bean.

1.4.2 injected beans

You can inject other Bean objects by injecting internal beans.

The configuration is as follows:

1 <bean id="user" class="com.demo.spring.User">
2     <property name="name" value="Zhang San"></property>
3     <property name="address">
4         <bean id="sz" class="com.demo.spring.Address">
5             <property name="province" value="Guangdong Province"></property>
6             <property name="city" value="Shenzhen City"></property>
7         </bean>
8     </property>
9 </bean>

1.4.3 injection cascade properties

You can inject attributes of other beans, that is, cascade attributes.

You need to provide the getter method of the Bean and the getter method of the Bean attribute.

The configuration is as follows:

1 <property name="address.province" value="Shandong Province"></property>

1.4.4 automatic assembly

You can automatically reference other Bean objects according to the assembly method, which is not often used.

The configuration is as follows:

1 <bean id="sz" class="com.demo.spring.Address">
2     <property name="province" value="Guangdong Province"></property>
3     <property name="city" value="Shenzhen City"></property>
4 </bean>
5 <bean id="user" class="com.demo.spring.User" autowire="byName">
6     <!--<property name="address" ref="sz"></property>-->
7 </bean>

Attribute description in bean tag:

autowire property: how the external Bean is referenced.

The autowire property has the following values:

byName: assemble according to the attribute name. In this way, beans with the same id and property name will be found in the configuration file. If multiple beans are found, an error will be reported. If none is found, null will be set.

byType: assemble according to the attribute type. In this way, beans with the same attribute type will be found in the configuration file. If multiple beans are found, an error will be reported. If none is found, null will be set.

Constructor: assemble according to the constructor. Not often.

Default: no automatic assembly, set the property to null. This method is used by default.

1.5 injection set attributes

1.5.1 injection array properties

You need to define array properties and provide setter methods.

The configuration is as follows:

 1 <bean id="audi" class="com.demo.spring.Car">
 2     <property name="brand" value="audi"></property>
 3     <property name="color" value="white"></property>
 4 </bean>
 5 <bean id="user" class="com.demo.spring.User">
 6     <property name="name" value="Zhang San"></property>
 7     <property name="pets">
 8         <array>
 9             <value>cat</value>
10             <value>dog</value>
11         </array>
12     </property>
13     <property name="cars">
14         <array>
15             <ref bean="audi"></ref>
16             <bean id="volvo" class="com.demo.spring.Car">
17                 <property name="brand" value="Volvo"></property>
18                 <property name="color" value="black"></property>
19             </bean>
20         </array>
21     </property>
22 </bean>

Label description is as follows:

Array tag: defines array properties.

value tag: defines the basic type and string type members in the array.

ref tag: defines the members of reference types in the array, and externally injects beans.

Bean tag: defines the members of reference types in the array and injects beans internally.

1.5.2 injection List attribute

You need to define the List property and provide the setter method.

The configuration is as follows:

 1 <bean id="audi" class="com.demo.spring.Car">
 2     <property name="brand" value="audi"></property>
 3     <property name="color" value="white"></property>
 4 </bean>
 5 <bean id="user" class="com.demo.spring.User">
 6     <property name="name" value="Zhang San"></property>
 7     <property name="pets">
 8         <list>
 9             <value>cat</value>
10             <value>dog</value>
11         </list>
12     </property>
13     <property name="cars">
14         <list>
15             <ref bean="audi"></ref>
16             <bean id="volvo" class="com.demo.spring.Car">
17                 <property name="brand" value="Volvo"></property>
18                 <property name="color" value="black"></property>
19             </bean>
20         </list>
21     </property>
22 </bean>

Label description is as follows:

List tag: defines the list attribute.

value tag: defines the basic type and string type members in the List.

ref tag: defines members of reference types in the List, and externally injects beans.

Bean tag: defines the members of the reference type in the List, and injects beans internally.

1.5.3 injection Set attribute

You need to define the Set property and provide the setter method.

The configuration is as follows:

 1 <bean id="audi" class="com.demo.spring.Car">
 2     <property name="brand" value="audi"></property>
 3     <property name="color" value="white"></property>
 4 </bean>
 5 <bean id="user" class="com.demo.spring.User">
 6     <property name="name" value="Zhang San"></property>
 7     <property name="pets">
 8         <set>
 9             <value>cat</value>
10             <value>dog</value>
11         </set>
12     </property>
13     <property name="cars">
14         <set>
15             <ref bean="audi"></ref>
16             <bean id="volvo" class="com.demo.spring.Car">
17                 <property name="brand" value="Volvo"></property>
18                 <property name="color" value="black"></property>
19             </bean>
20         </set>
21     </property>
22 </bean>

Label description is as follows:

Set tag: defines the set property.

value tag: defines the basic type and string type members in the Set.

ref tag: defines members of reference types in a Set, and externally injects beans.

Bean tag: defines the members of the reference type in the Set, and injects beans internally.

1.5.4 inject Map attribute

You need to define the Map property and provide the setter method.

The configuration is as follows:

 1 <bean id="audi" class="com.demo.spring.Car">
 2     <property name="brand" value="audi"></property>
 3     <property name="color" value="white"></property>
 4 </bean>
 5 <bean id="mazda" class="com.demo.spring.Car">
 6     <property name="brand" value="Mazda"></property>
 7     <property name="color" value="gules"></property>
 8 </bean>
 9 <bean id="user" class="com.demo.spring.User">
10     <property name="name" value="Zhang San"></property>
11     <property name="pets">
12         <map>
13             <entry key="cat" value="cat"></entry>
14             <entry key="dog" value="dog"></entry>
15         </map>
16     </property>
17     <property name="cars">
18         <map>
19             <entry key="audi" value-ref="audi"></entry>
20             <entry key="Mazda" value-ref="mazda"></entry>
21             <entry key="Volvo">
22                 <bean id="volvo" class="com.demo.spring.Car">
23                     <property name="brand" value="Volvo"></property>
24                     <property name="color" value="black"></property>
25                 </bean>
26             </entry>
27         </map>
28     </property>
29 </bean>

Label and attribute description are as follows:

Map tag: defines the map attribute.

entry tag: defines the members in the Map.

Key attribute: defines the key of the basic type and string type in the Map.

Key ref attribute: defines the key of the reference type in the Map.

Value attribute: defines the value of the basic type and string type in the Map.

Value ref attribute: defines the value of the reference type in the Map, and externally injects the Bean.

Bean tag: defines the value of the reference type in the Map and injects the bean internally.

1.6 extract set attributes

Using the util namespace, the collection properties can be extracted as a single Bean.

util namespace needs to be added:

1 <beans xmlns="http://www.springframework.org/schema/beans"
2        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3        xmlns:util="http://www.springframework.org/schema/util"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
5                            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

The configuration is as follows:

 1 <util:map id="pets">
 2     <entry key="cat" value="cat"></entry>
 3     <entry key="dog" value="dog"></entry>
 4 </util:map>
 5 <util:map id="cars">
 6     <entry key="audi" value-ref="audi"></entry>
 7     <entry key="Mazda" value-ref="mazda"></entry>
 8     <entry key="Volvo">
 9         <bean id="volvo" class="com.demo.spring.Car">
10             <property name="brand" value="Volvo"></property>
11             <property name="color" value="black"></property>
12         </bean>
13     </entry>
14 </util:map>
15 <bean id="audi" class="com.demo.spring.Car">
16     <property name="brand" value="audi"></property>
17     <property name="color" value="white"></property>
18 </bean>
19 <bean id="mazda" class="com.demo.spring.Car">
20     <property name="brand" value="Mazda"></property>
21     <property name="color" value="gules"></property>
22 </bean>
23 <bean id="user" class="com.demo.spring.User">
24     <property name="name" value="Zhang San"></property>
25     <property name="pets" ref="pets"></property>
26     <property name="cars" ref="cars"></property>
27 </bean>

2 manage factory Bean

2.1 what is it

There are two types of beans in Spring, one is an ordinary Bean and the other is a factory Bean.

For ordinary beans, the Bean type defined in the configuration file is to obtain the return type of the Bean. However, for factory beans, the Bean type defined in the configuration file is not the return type of the obtained Bean.

To create a factory Bean:

1) Create factory classes, implement FactoryBean interfaces and methods.

2) Define the returned Bean type in the implemented method.

2.2 use

Create factory class:

 1 public class Animal implements FactoryBean<Cat> {
 2     @Override
 3     public Cat getObject() throws Exception {
 4         return new Cat();
 5     }
 6     @Override
 7     public Class<?> getObjectType() {
 8         return null;
 9     }
10 }

To create an object in a configuration file:

1 <bean id="cat" class="com.demo.spring.Animal"></bean>

Test:

1 @Test
2 public void testAdd() {
3     // Load profile
4     ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
5     // Get configured object
6     Cat cat = context.getBean("cat", Cat.class);
7     // Use object
8     System.out.println(cat);
9 }

3 scope of bean

3.1 default

When the IOC container is created, all objects in the configuration file will be created and initialized.

The object created by default is single instance, that is, the object obtained multiple times is the same object.

Test:

1 @Test
2 public void testAdd() {
3     ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
4     System.out.println(context.getBean("cat", Cat.class));
5     System.out.println(context.getBean("cat", Cat.class));
6 }

The addresses obtained twice are the same, indicating that they are the same object, and the table name is singleton by default.

3.2 configuration

In the configuration file, you can use the scope attribute of the bean tag to modify the way the object is created.

Value of scope attribute:

1 singleton: Single instance. Objects are created during container initialization. The default configuration method is.
2 prototype: Multi instance. Objects are not created during container initialization. Objects are created each time they are used. Objects can be selected dynamically.
3 request: stay Web In the project, objects are not created during container initialization, and objects are created for each request.
4 session: stay Web In the project, objects are not created during container initialization, and objects are created for each session.

The configuration examples are as follows:

1 <bean id="cat" class="com.demo.spring.Animal" scope="prototype"></bean>

4. Bean life cycle

4.1 what is it

The life cycle of a Bean refers to the whole process from creation to destruction.

4.2 life cycle

4.2.1 sequence

1) Create a Bean instance through a parameterless constructor.

2) Set the reference between the attribute value and the Bean for the Bean.

3) To execute the Bean initialization method, you need to set the method.

4) Get and use beans.

5) To execute the Bean's destruction method, you need to set the method to be called automatically when you manually destroy the container.

4.2.2 demonstration

Create class:

 1 public class User {
 2     public String name;
 3     public User() {
 4         System.out.println("Step1 Created by a parameterless constructor Bean example");
 5     }
 6     public void setName(String name) {
 7         System.out.println("Step2 to Bean Set attribute values and Bean References between");
 8         this.name = name;
 9     }
10     public void initMethod() {
11         System.out.println("Step3 implement Bean Initialization method of");
12     }
13     public void destroyMethod() {
14         System.out.println("Step5 implement Bean Destruction method of");
15     }
16 }

Profile:

1 <bean id="user" class="com.demo.spring.User" init-method="initMethod" destroy-method="destroyMethod">
2     <property name="name" value="Zhang San"></property>
3 </bean>

Test method:

1 @Test
2 public void testAdd() {
3     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
4     User user = context.getBean("user", User.class);
5     System.out.println("Step4 Get and use Bean");
6     System.out.println(user);
7     // Step5 Manually destroy the container and execute Bean Destruction method of
8     context.close();
9 }

Execution results:

1 Step1 Created by a parameterless constructor Bean example
2 Step2 to Bean Set attribute values and Bean References between
3 Step3 implement Bean Initialization method of
4 Step4 Get and use Bean
5 com.demo.spring.User@5123a213
6 Step5 implement Bean Destruction method of

4.3 post processor

4.3.1 definitions

The post processor will execute the corresponding methods before and after executing the initialization method of the Bean. The interface needs to be implemented and configured in the configuration file.

The post processor will add processing methods for all Bean instances in the current configuration file.

4.3.2 demonstration

To create a postprocessor class:

 1 public class DemoBeanPost implements BeanPostProcessor {
 2     @Override
 3     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
 4         System.out.println("Step3 implement Bean Before the initialization method of");
 5         return bean;
 6     }
 7     @Override
 8     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
 9         System.out.println("Step3 implement Bean After the initialization method of");
10         return bean;
11     }
12 }

Profile:

1 <bean id="demoBeanPost" class="com.demo.spring.DemoBeanPost"></bean>

Execution results:

1 Step1 Created by a parameterless constructor Bean example
2 Step2 to Bean Set attribute values and Bean References between
3 Step3 implement Bean Before the initialization method of
4 Step3 implement Bean Initialization method of
5 Step3 implement Bean After the initialization method of
6 Step4 Get and use Bean
7 com.demo.spring.User@24b1d79b
8 Step5 implement Bean Destruction method of

5. Import external files

Using the context namespace, you can import external files and use their configurations, which are mostly used to create database connection pools.

Need to add context namespace:

1 <beans xmlns="http://www.springframework.org/schema/beans"
2        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3        xmlns:context="http://www.springframework.org/schema/context"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
5                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

The configuration is as follows:

1 <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
2 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
3     <property name="username" value="${mysql.username}"></property>
4     <property name="password" value="${mysql.password}"></property>
5     <property name="url" value="${mysql.url}"></property>
6     <property name="driverClassName" value="${mysql.driver}"></property>
7 </bean>

 

Keywords: Spring

Added by achintha on Wed, 19 Jan 2022 10:14:34 +0200