Spring learning summary (four): assembly Bean based on XML (2)

One, inject null values ​​and special symbols

1. Inject a null value

       (1) Create entity class User, provide private attributes name, age and address, and provide their set method and toString().

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

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setAddress(String address) {
        this.address = address;
    }

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

       (2) Configure the User object in bean.xml, and inject the name and age, and set the address to null.

<!--  向属性注入null值  -->
    <bean id="user" class="com.yht.example1.entity.User">
        <property name="name" value="刘备"></property>
        <property name="age" value="23"></property>
        <property name="address">
            <null></null>
        </property>
    </bean>

       (3) Perform unit testing.

    @Test
    public void testNull(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        User user = (User) context.getBean("user");
        System.out.println(user);
    }

       The execution results are as follows:

       Note: null and "" are not the same. If the value of address is set to "" , the execution result is as follows:

    <bean id="user" class="com.yht.example1.entity.User">
        <property name="name" value="刘备"></property>
        <property name="age" value="23"></property>
        <property name="address" value=""></property>
    </bean>

 

2. Inject special symbols

       There are two ways to inject special symbols: one is to use escape characters, such as <, >, etc.; the other is to use CDATA to complete, just write the content of special symbols into CDATA. Now suppose that when injecting a value into the bName property of the Book class, add the book title number "". The implementation is as follows:

       (1) Create the Book class, provide the bName and bAuthor attributes, and provide the parameter structure.

public class Book {
    private String bName;
    private String bAuthor;

    public Book(String bName, String bAuthor) {
        this.bName = bName;
        this.bAuthor = bAuthor;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bName='" + bName + '\'' +
                ", bAuthor='" + bAuthor + '\'' +
                '}';
    }
}

       (2) Attribute injection in bean.xml.

    <!-- 向属性注入特殊字符:使用转义字符   -->
    <bean id="book1" class="com.yht.example1.entity.Book">
        <constructor-arg name="bName" value="&lt;&lt;三国演义&gt;&gt;"></constructor-arg>
        <constructor-arg name="bAuthor" value="罗贯中"></constructor-arg>
    </bean>
    <!-- 向属性注入特殊字符: CDATA  -->
    <bean id="book2" class="com.yht.example1.entity.Book">
        <constructor-arg name="bName">
            <value><![CDATA[<<水浒传>>]]></value>
        </constructor-arg>
        <constructor-arg name="bAuthor" value="施耐庵"></constructor-arg>
    </bean>

        (3) Perform unit testing.

    @Test
    public void testSpecialChar(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        Book book1 = (Book) context.getBean("book1");
        System.out.println(book1);
        Book book2 = (Book) context.getBean("book2");
        System.out.println(book2);
    }

       The execution results are as follows:

Two, attribute injection

1, external bean

       The way of the external bean is to point the instance configured in bean.xml through the ref attribute . Let's simply implement the process of UserService and UserDao through Spring.

       (1) Create two classes UserService and UserDao respectively.

public class UserService {
    private UserDao userDao;

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

    public void execute(){
        userDao.findUser();
    }
}
public class UserDao {
    public void findUser(){
        System.out.println("查找用户");
    }
}

        (2) Assign and configure userService and userDao in bean.xml.

    <!--    外部注入bean-->
    <bean id="userService" class="com.yht.example2.service.UserService">
        <!--  ref 属性:创建的userDao对象的bean标签的id值     -->
        <property name="userDao" ref="userDao"></property>
    </bean>
    <bean id="userDao" class="com.yht.example2.dao.UserDao"></bean>

       (3) Perform unit testing.

@Test
    public void testOuterBean(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.execute();
    }

       The execution results are as follows:

 

        Note: The value in ref must be consistent with the id value of the specified bean instance.

2. Internal bean

       The inner bean is equivalent to a nested way. The difference between it and an external bean is that the internal bean does not need to write an id and cannot be accessed by the outside.

       (1) Create two entity classes: Emp and Dept.

public class Emp {
    private String empName;
    private Integer age;
    private Dept dept;

    

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

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

    @Override
    public String toString() {
        return "Emp{" +
                "empName='" + empName + '\'' +
                ", age=" + age +
                ", dept=" + dept +
                '}';
    }
}
public class Dept {
    private String deptName;

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "deptName='" + deptName + '\'' +
                '}';
    }
}

        (2) Configure the internal bean in bean.xml

    <!--    内部注入bean-->
    <bean id="emp" class="com.yht.example2.entity.Emp">
        <property name="empName" value="王飞"></property>
        <property name="age" value="21"></property>
        <property name="dept">
            <bean id="dept" class="com.yht.example2.entity.Dept">
                <property name="deptName" value="开发部"></property>
            </bean>
        </property>
    </bean>

       (3) Perform unit testing.

    @Test
    public void testInnerBean(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Emp emp = (Emp) context.getBean("emp");
        System.out.println(emp);
    }

       The execution results are as follows:

 

3. Cascading beans

       Spring supports the configuration of cascading attributes. Spring does not limit the number of levels of cascading attributes. As long as the configured Bean has a class structure corresponding to the cascading attributes, any level of cascading attributes can be configured. There are two ways to configure cascading attributes: one is the way of external beans; the other is to provide the get method of the attribute in the entity class, and then complete it through the. Operator in the configuration file.

       (1) Add a get method to the dept attribute in the Emp class.

    public Dept getDept() {
        return dept;
    }

       (2) Configure in bean.xml.

    <!--        级联bean 方式一  -->
    <bean id="employee1" class="com.yht.example2.entity.Emp">
        <property name="empName" value="张帆"></property>
        <property name="age" value="11"></property>
        <property name="dept" ref="dept"></property>
    </bean>
    <bean id="dept" class="com.yht.example2.entity.Dept">
        <property name="deptName" value="开发部"></property>
    </bean>
    <!--    方式二   -->
    <bean id="employee2" class="com.yht.example2.entity.Emp">
        <property name="empName" value="康特"></property>
        <property name="age" value="32"></property>
        <property name="dept" ref="dept"></property>
        <property name="dept.deptName" value="安保部"></property>
    </bean>

       (3) Perform unit testing.

    @Test
    public void testContactBean(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Emp emp1 = (Emp) context.getBean("employee1");
        System.out.println(emp1);
        Emp emp2 = (Emp) context.getBean("employee2");
        System.out.println(emp2);
    }

       The execution results are as follows:

3. Injection of common data types

1. Injection of basic data types and collection types

       The basic data types in Spring include the eight basic data types in Java and the String type. Here we explain the injection methods of basic data types, Array, list, set, and Map respectively.

       (1) Create the ParaTest class.

public class ParaTest {
    private String name;
    private String[] strings;
    private List<Integer> lists;
    private Set<Double> sets;
    private Map<Character, String> map;

    public void setName(String name) {
        this.name = name;
    }

    public void setStrings(String[] strings) {
        this.strings = strings;
    }

    public void setLists(List<Integer> lists) {
        this.lists = lists;
    }

    public void setSets(Set<Double> sets) {
        this.sets = sets;
    }

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

    public void showMessage(){
        System.out.println("name is : " + this.name);
        System.out.println("Strings content are : " + Arrays.toString(this.strings));
        System.out.println("lists content are  : " + this.lists);
        System.out.println("sets content are  : " + this.sets);
        System.out.println("map content are  : " + this.map);
    }
}

       (2) Configure objects in bean.xml and inject values.

    <!--  测试基本数据类型和集合数据类型  -->
    <bean id="para" class="com.yht.example2.entity.ParaTest">
        <!--   注入String     -->
        <property name="name" value="郑秀"></property>
        <!--   注入数组     -->
        <property name="strings">
            <array>
                <value>魏国</value>
                <value>蜀国</value>
                <value>吴国</value>
            </array>
        </property>
        <!--   注入list     -->
        <property name="lists">
            <list>
                <value>13</value>
                <value>35</value>
                <value>57</value>
            </list>
        </property>
        <!--   注入set     -->
        <property name="sets">
            <set>
                <value>12.5</value>
                <value>754.1</value>
                <value>89.0</value>
            </set>
        </property>
        <!--   注入map     -->
        <property name="map">
            <map>
                <entry key="a" value="Apple"></entry>
                <entry key="b" value="bar"></entry>
                <entry key="c" value="car"></entry>
                <entry key="d" value="department"></entry>
            </map>
        </property>
    </bean>

       (3) Perform unit testing.

    @Test
    public void testPara(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        ParaTest para = (ParaTest) context.getBean("para");
        para.showMessage();
    }

       The execution results are as follows:

2. Injection of object type

       Under normal circumstances, we are more likely to use injection object types. There are many books for one person, so how to achieve it?

        (1) Add List<Book> to the Person class and provide the set method ().

    private List<Book> bookList;

    public void setBookList(List<Book> bookList) {
        this.bookList = bookList;
    }

       (2) Configure in bean.xml.

    <!--  注入对象类型  -->
    <bean id="bookPerson" class="com.yht.example1.entity.Person">
        <property name="name" value="赵峰"></property>
        <property name="age" value="45"></property>
        <property name="bookList">
            <list>
                <ref bean="b1"></ref>
                <ref bean="b2"></ref>
            </list>
        </property>
    </bean>
    <bean id="b1" class="com.yht.example1.entity.Book">
        <constructor-arg name="bName" value="三国演义"></constructor-arg>
        <constructor-arg name="bAuthor" value="罗贯中"></constructor-arg>
    </bean>
    <bean id="b2" class="com.yht.example1.entity.Book">
        <constructor-arg name="bName" value="水浒传"></constructor-arg>
        <constructor-arg name="bAuthor" value="施耐庵"></constructor-arg>
    </bean>

       (3) Perform unit testing.

    @Test
    public void testObjectPara(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        Person person= (Person) context.getBean("bookPerson");
        System.out.println(person);
    }

       The results are as follows:

 3. Extract the public part

       Now suppose that there are many individuals whose books are the same, and the books need to be extracted as a public part. Proceed as follows:

       (1) Introduce the namespace util in the spring configuration file.

<?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: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 http://www.springframework.org/schema/util/spring-util.xsd">

       (2) Use the util tag to complete the list collection injection and extraction.

<?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: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 http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="b1" class="com.yht.example1.entity.Book">
        <constructor-arg name="bName" value="三国演义"></constructor-arg>
        <constructor-arg name="bAuthor" value="罗贯中"></constructor-arg>
    </bean>
    <bean id="b2" class="com.yht.example1.entity.Book">
        <constructor-arg name="bName" value="水浒传"></constructor-arg>
        <constructor-arg name="bAuthor" value="施耐庵"></constructor-arg>
    </bean>
    <!--把集合注入部分提取出来-->
    <!-- 提取list集合类型属性注入-->
    <util:list id="bookList">
        <ref bean="b1"></ref>
        <ref bean="b2"></ref>
    </util:list>

    <!-- 提取list集合类型属性注入使用-->
    <bean id="person1" class="com.yht.example1.entity.Person" scope="prototype">
        <property name="name" value="王刚"></property>
        <property name="age" value="40"></property>
        <property name="bookList" ref="bookList"></property>
    </bean>
    <bean id="person2" class="com.yht.example1.entity.Person" scope="prototype">
        <property name="name" value="张凡"></property>
        <property name="age" value="32"></property>
        <property name="bookList" ref="bookList"></property>
    </bean>
</beans>

       (3) Perform unit testing.

    @Test
    public void testCommonContent(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
        Person person1 = (Person) context.getBean("person1");
        System.out.println(person1);
        Person person2 = (Person) context.getBean("person2");
        System.out.println(person2);
    }

       The execution results are as follows:

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/112757551
Recommended