Bean management of IOC specific operations

Posted by jaxxstorm on Sat, 19 Feb 2022 00:43:25 +0100

Bean management of IOC specific operations (based on xml)

What is Bean management?

Bean management actually refers to two operations. The first is to create objects for us by Spring, that is, through bean tags, and then create objects. The second is property injection by Spring. For example, a java bean has a private String userName attribute. We can set the attribute through setter. Now this process can also be left to Spring. This process is called property injection.

objects creating

In Spring's xml configuration file, you can create objects by using bean tags and adding corresponding attributes in the tags.

<bean id="sutdent" class="com.zxb.spring.bean.Student"></bean>

In this way, we create an object (created by parameterless construction).

There are many properties in the bean tag. Here are the commonly used properties.

*id attribute: unique identification. It means to give an object an identity or alias, and then get the object through the identity or alias.

*Class attribute: class full path (package class path)

*Name attribute: the function of name attribute and id attribute is the same. The difference is that special symbols cannot be added to id attribute, but some special symbols can be added to name, such as /. Now almost no one uses it. It was originally born for struts 1.

be careful! When creating an object, the default is to execute the construction method without parameters to complete the creation of the object. Most of the frameworks use newInstance() to create objects. This method also calls parameterless construction, so it is necessary to write parameterless construction. If you write it correctly, you will write it correctly.

Attribute injection

DI(Dependency Injection): dependency injection is the injection attribute.

The first injection mode

Inject using the set method. You need to create properties and corresponding set methods in the class.

<bean id="book" class="com.zxb.spring.Book">
        <!--The injection attribute should be written in bean Inside the tag, it is equivalent to the object calling method-->
        <!--
		   use property Complete attribute injection
            name: The name of the attribute in the class
            value: Values injected into attributes
        -->
        <property name="bname" value="java From getting started to giving up"></property>
        <property name="bauthor" value="Hair Care Secrets"></property>
    </bean>

When ApplicationContext = new classpathxmlapplicationcontext ("xxx.xml"); When loading the configuration file, it will help us complete object creation and attribute injection.

Through set injection, you need to write the property attribute inside the bean tag, which is more troublesome. Another operation that simplifies xml configuration is called p namespace injection. This method simplifies set injection rather than constructor injection.

Step 1: add p namespace in the configuration file.

xmlns:p="http://www.springframework.org/schema/p"

Step 2: conduct attribute injection and operate in the bean tag

<bean id="book" class="com.zxb.spring.bean.Book" p:bname="nine men's power" p:bauthor="anonymous person"></bean>

The underlying method of this injection through p namespace is set injection. It's just simplified.

The second injection mode

Attribute injection using parameterized constructs
Step 1: create a class, define an attribute, and create a parametric construction method corresponding to the attribute.
Step 2: configure in the Spring configuration file.

<!--Inject attributes through parametric construction-->
    <bean id="orders" class="com.zxb.spring.bean.Orders">
        <constructor-arg name="oName" value="computer"></constructor-arg>
        <constructor-arg name="address" value="China"></constructor-arg>
        <!--
        <constructor-arg index="0" value="computer"></constructor-arg>
        <constructor-arg index="1" value="China"></constructor-arg>
        -->
    </bean>

It is also possible to use the index, which represents the parameters of the construction method. But generally use name, which is more accurate.

be careful!

I

If there is no constructor in the class, only attributes are written. In the xml file, only attributes can be written

< bean id = "student1" class = "com. ZXB. Spring. Bean. Student" > < / bean >, which will help us create an object with default properties. If you define the bean tag in this way, you cannot write property inside the bean tag because there is no corresponding setter. Only by writing setter can we inject properties.

II

If the property is written in the class, but the parameterless construction is not written, but there is a corresponding parameterless construction method, only

< bean id = "student1" class = "com. ZXB. Spring. Bean. Student" > < / bean > will report an error. This is to find a parameterless structure, but we did not write a parameterless structure. We need to add a constructor Arg tag to the bean tag to assign a value to the parameter.

In a word, only write < bean id = "student1" class = "com. ZXB. Spring. Bean. Student" > < / bean > to find the parameterless structure. If the attribute is written in the bean tag, the corresponding setter will be found. If not, an error will be reported.

xml injection other types of attributes

1. Literal quantity

The fixed value used in setting is called literal. For example, private String oName = "zs"; Here zs is the literal quantity. It's fixed. You can also set fixed values through the name and value in the property tag. These fixed values are also called literal values.

(1)null value

<property name="address"  >
    <null></null>
    <null/>Single label and double label are OK
</property>

(2) the attribute value contains the special symbol < >, etc

Method 1: Use & L T; Or & G T;

<!--Attribute values contain special symbols-->
<property name="address" value="&lt;Hangzhou&gt;"></property>

Method 2: CDATA domain

Note that value can be written inside the property tag as a tag.

<property name="address">
    <value> <![CDATA[<Hangzhou>]]> </value>
</property>

Injection properties - External bean s

For example, there are three layers in the operation. The web layer calls the service layer, and the service layer calls the dao layer. Now write two layers, one is the service layer and the other is the dao layer. Calling dao through service is called importing external bean s.

        //Original method: create UserDao object
		//UserDao userDao = new UserDaoImpl();
		//userDao.update();

(1) create two classes, service and dao

(2) call the method in dao in service

(3) configure in the Spring configuration file

java code:

public class UserService {

    //Create UserDao type attribute and generate set method
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void add() {
        System.out.println("service add...");
        userDao.update();
    }
}

xml configuration:

<!--1 service and dao objects creating-->
    <bean id="userService" class="com.zxb.spring.service.UserService">
        <!--2 injection userDao object
            name Attribute, the name of the specified attribute in the class
            ref Properties, creating userDao Object bean Label of id,Indicates that I need external bean,ref It's the outside bean of id. 
        -->
        <property name="userDao" ref="userDaoImpl"></property>
    </bean>
    <bean id="userDaoImpl" class="com.zxb.spring.dao.UserDaoImpl"></bean>

**For the injection of external beans, when other classes need to be used in the current class, we only need to create the variable name of an external class, and then create the set method of the variable name. Then configure the bean tags of the current class and external class in xml, that is, other classes we need. In the bean tag of the current class, use the ref attribute of the property tag to inject external beans. The value of the ref attribute is the id value of the external bean.
**

Injection properties - internal bean s

(1) One to many relationships: departments and employees

There can be multiple employees in a department. One employee belongs to one department.

The Department is one, and there are many employees.

(2) One to many relationships are represented between entity classes. Employees represent their departments and are represented by object class attributes.

package com.zxb.spring.bean;

//Employee category
public class Emp {
    private String eName;
    private String gender;
    //Employees belong to a department and are represented in the form of objects
    private Dept dept;

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    public void seteName(String eName) {
        this.eName = eName;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

package com.zxb.spring.bean;

//Department category
public class Dept {
    private String dName;

    public void setdName(String dName) {
        this.dName = dName;
    }
}

(3) Configure in the Spring configuration file

<!--inside bean-->
    <bean id="emp" class="com.zxb.spring.bean.Emp">
        <!--First set two common properties-->
        <property name="eName" value="lucy"></property>
        <property name="gender" value="female"></property>
        <!--You can create an external object by setting the object type property bean(object),Pass again ref introduce
            But this is external bean We can write in property Nested in a label bean
        -->
        <property name="dept">
            <bean id="dept" class="com.zxb.spring.bean.Dept">
                <property name="dName" value="Security Department"></property>
            </bean>
        </property>
    </bean>

An internal bean is a bean tag nested inside the property tag.

Injection properties – cascade assignment (via external beans)

We still use the example of employees and departments. For example, when we want to assign a value to emp, we also assign a value to dname in dept. In fact, we have done it before. Now we use another way to do cascade assignment. You can set values to your associated properties at the same time. For example, set values for all the attributes in the Department. Is to set its attribute value to multiple entity classes.

Writing method 1:

<!--Cascade assignment-->
    <bean id="emp" class="com.zxb.spring.bean.Emp">
        <!--First set two common properties-->
        <property name="eName" value="lucy"></property>
        <property name="gender" value="female"></property>
        <!--Cascade assignment, the first way to write-->
        <property name="dept" ref="dept"></property>
    </bean>
    <bean id="dept" class="com.zxb.spring.bean.Dept">
        <property name="dName" value="Finance Department"></property>
    </bean>

Writing method 2:

<!--Cascade assignment-->
    <bean id="emp" class="com.zxb.spring.bean.Emp">
        <!--First set two common properties-->
        <property name="eName" value="lucy"></property>
        <property name="gender" value="female"></property>
        <property name="dept" ref="dept"></property>
        <!--Cascade assignment, the second way
            need get Method to get properties(object)
            Because they are private methods, set Used to assign values,
            get Used to get, and then get the object type, and then through the object.Properties,
            Pass again value Assign values.
        -->
        <property name="dept.dName" value="Security Department"></property>
    </bean>
    <bean id="dept" class="com.zxb.spring.bean.Dept"></bean>

Injection attributes – set attributes

1. Inject array type properties

2. Inject List properties

3. Injection Map collection type

(1) create classes, define array, list, map and set type attributes, and generate their set methods.

package com.zxb.spring.collectiontype;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class Stu {
    //1. Array type properties
    private String[] courses;

    //2. list collection type attribute
    private List<String> list;

    //3. map collection type attribute
    private Map<String, String> map;

    //4. set collection type property
    private Set<String> set;

    public void setCourses(String[] courses) {
        this.courses = courses;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }
}

(2) Configure in the Spring configuration file

Array type injection is required because there are multiple values and the value attribute of the property tag can only be assigned one value

<property name="courses">
    <array>
    	<value></value>
        ...
    </array>
</property>
or
<property name="courses">
     <list>
        <value></value>
        ...
    </list>
</property>
<!--Collection type attribute injection-->
    <bean id="stu" class="com.zxb.spring.collectiontype.Stu">
        <!--Array type attribute injection-->
        <property name="courses">
            <array>
                <value>java people</value>
                <value>java soul</value>
            </array>
        </property>
        <!--list Type attribute injection-->
        <property name="list">
            <array>
                <value>Zhang San</value>
                <value>the other woman</value>
            </array>
        </property>

        <!--map Type attribute injection-->
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"></entry>
                <entry key="PHP" value="php"></entry>
            </map>
        </property>

        <!--set Type attribute injection-->
        <property name="sets">
            <set>
                <value>MySQL</value>
                <value>Redis</value>
            </set>
        </property>
    </bean>

4. Set the object type value in the collection

Using the bean attribute in the ref tag, the id values of multiple objects are written in the bean.

Configure the following in xml

		<property name="courseList"> <!-- This property is List<Course>Type, injected Course type -->
            <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
            </list>
        </property>

	    <!--Create multiple external course object-->
	    <bean id="course1" class="com.zxb.spring.collectiontype.Course">
	        <property name="cname" value="Spring frame"></property>
	    </bean>
	    <bean id="course2" class="com.zxb.spring.collectiontype.Course">
	        <property name="cname" value="MyBatis frame"></property>
	    </bean>

5. Extract the set injection part as a public part

(1) introduce the namespace util into the Spring configuration file.

The first step is to add in the bean tag

xmlns:util="http://www.springframework.org/schema/util"

Step 2: continue to add the following in the bean tag

http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd

Just change beans to util.

The results are as follows

<?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"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">

(2) use the util tag to complete the list collection attribute extraction, so that other bean s can also use this attribute.

<!-- 1,use util extract list Collection properties -->
    <!--util Can extract list,map,set etc.
        this id Equivalent to name, equivalent to taking a public name from a public class
    -->
    <util:list id="bookList">
        <!--If there are basic data types in the collection, use value label
            If there are class types in the collection, use ref Tagged bean attribute
        -->
        <value>Yi Jin Jing</value>
        <value>The nine Yin manual</value>
        <value>nine men's power</value>
    </util:list>

    <!-- 2,Inject the extracted attributes of the object -->
    <bean id="book" class="com.zxb.spring5.collectiontype.Book">
        <!--use ref The tag injects the extracted attributes, which will bookList The value in is injected directly into the attribute
            So if there are multiple bean,You can pass ref To inject attributes.
        -->
        <property name="list" ref="bookList"></property>
    </bean>

Topics: Java Spring xml bean