Spring learning summary (three): assembly Bean based on XML (1)

1. Bean assembly

       The assembly of Bean can be understood as dependency injection, and the assembly method of Bean is also the dependency injection method of Bean. The Spring container supports multiple forms of Bean assembly, such as XML-based Bean assembly, Annotation-based Bean assembly, and automatic assembly.

       Spring XML-based assembly usually adopts two implementation methods, namely set injection and construction injection.

1. Set injection

       In the process of instantiating a Bean in Spring, the default construction method is first invoked to instantiate the Bean object, and then the setXxx() method is invoked for property injection through the Java reflection mechanism. Therefore, set value injection requires that the corresponding class of a Bean must meet the following two requirements:

  • A default no-argument construction method must be provided.
  • Corresponding setter methods must be provided for the properties that need to be injected.

       Next, I will use a simple case to demonstrate set injection. Proceed as follows:

       (1) Create the Person class and provide private attributes name and age and their set methods, overriding toString().

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

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

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

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

       (2) Configure the person object in the bean.xml file, and inject the attribute value using set injection.

    <!--  配置Person  -->
    <bean id="person" class="com.yht.example1.entity.Person">
        <!--  name:类中属性的名称  value:向属性注入的值     -->
        <property name="name" value="张三"></property>
        <property name="age" value="33"></property>
     </bean>

       (3) Perform unit testing

    @Test
    public void testPerson(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person);
       
    }

        The execution results are as follows:

2. Structural injection

       When setting value injection is used, in the Spring configuration file, you need to use the sub-element <property> of the <bean> element to inject values ​​for each property. When using construction injection, in the configuration file, the <constructor-arg> tag is mainly used to define the parameters of the construction method, and the value attribute (or sub-element) can be used to set the value of the parameter. The following example demonstrates the assembly of Bean based on XML.

       There are two ways to construct injection: the first is done by the child element name of <constructor-arg>; the second is done by the child element index of <constructor-arg>, where index refers to the attribute in the construction method Subscript, starting from 0 . Let's do a simple test:

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

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) Configure the person object in bean.xml, and inject property values ​​by constructing injection.

    <!-- 配置book:用name的方式   -->
    <bean id="book1" class="com.yht.example1.entity.Book">
        <constructor-arg name="bName" value="三国演义"></constructor-arg>
        <constructor-arg name="bAuthor" value="罗贯中"></constructor-arg>
    </bean>
    <!-- 配置book:用index的方式   -->
    <bean id="book2" 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 testBook(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        //获取用name注入的对象
        Book book1 = (Book) applicationContext.getBean("book1");
        System.out.println(book1);
        //获取用index注入的对象
        Book book2 = (Book) applicationContext.getBean("book2");
        System.out.println(book2);
    }

        The execution results are as follows:

3. p namespace injection

Starting from 2.0, Spring supports an extensible configuration format that uses namespaces. These namespaces are based on an XML Schema definition. In fact, the configuration format of all the beans we have seen is based on an XML Schema document.

The p namespace does not need to be defined in an XSD file. It only exists in the Spring core. Using the p namespace, you can use attributes in the bean element to describe the value of the property.

Writing method:

Common attribute p: attribute name = "value"

Object attribute p: attribute name-ref=”value”

Precautions:

The P namespace injection is also the set method. The official purpose is to simplify the writing of the property tag of set injection, so it is not suitable for construction injection.

       Let's take the attribute value of the Person object injected as an example, the steps are as follows:

       (1) Import the p namespace in bean.xml.

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

        (2) Configure the person object and inject attributes.

    <!-- p名称空间注入   -->
    <bean id="person2" class="com.yht.example1.entity.Person" p:name="李四" p:age="24" >
    </bean>

       (3) Perform unit testing.

    @Test
    public void testPerson(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
        //set注入
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person);
        //p名称空间注入
        Person person2 = (Person) applicationContext.getBean("person2");
        System.out.println(person2);
    }

        The execution results are as follows:

Two, some explanations of Bean assembly

1. The child element name of the bean

       In addition to the id and class attributes of the bean, there is also a name attribute. The Spring container can configure and manage the Bean in the container through this attribute. The name attribute can specify multiple names for the Bean, with a comma or semicolon between each name. Separate, and can contain special characters. Let's use a case to verify:

       (1) Configure the person object in bean.xml and give multiple values.

<!--  测试bean的name属性  -->
    <bean class="com.yht.example1.entity.Person" name="p1,p2,p3@">
        <property name="name" value="赵飞"></property>
        <property name="age" value="23"></property>
    </bean>

       (2) Perform unit testing.

    @Test
    public void testPersonP(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
        Person p1 = (Person) applicationContext.getBean("p1");
        System.out.println(p1);
        Person p2 = (Person) applicationContext.getBean("p2");
        System.out.println(p2);
        Person p3 = (Person) applicationContext.getBean("p3@");//含有特殊字符
        System.out.println(p3);
    }

       The execution results are as follows:

       Note: No matter it is id or name, its value cannot be repeated. That is: between id, name, id and name must be unique. as follows:

2. Can set injection and structure injection be mixed?

       (1) Make some modifications to the Person class, adding a parameter-free structure and a parameter-containing structure with name.

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

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

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

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

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

       (2) Configure the Person object in bean.xml and inject properties

    <!--set注入和构造注入混合使用-->
    <bean id="per" class="com.yht.example1.entity.Person">
        <constructor-arg name="name" value="tom"></constructor-arg>
        <property name="age" value="41"></property>
    </bean>

       (3) Perform unit testing.

    @Test
    public void testPer(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
        Person per = (Person) applicationContext.getBean("per");
        System.out.println(per);
    }

       The execution results are as follows:

       Conclusion: Set injection and structure injection can be used at the same time, but it is not recommended. 

Guess you like

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