Spring learning summary (6): Bean assembly based on XML (4)

1. Automatic assembly

      If there are many properties in a bean, each property must be manually added with a property node to explicitly inject the property value, which is very troublesome. When configuring metadata based on XML, you can use the autowire attribute of the bean element to specify a specific automatic assembly mode.

There are two ways to use Autowire to remove the <property> tag:

  • It can be configured under the root tag of <beans>, which means it works on the global <bean>, and the attribute name is default-autowire
  • It can be configured under the <bean> tag, which means it works on the current <bean>, and the attribute name is autowire

      The autowire attribute mainly has the following values:

Attributes Description
no

The default setting means that it does not use automatic assembly mode.

byName

Automatic assembly by attribute name. The Spring container sees that the bean adopts the automatic assembly byName mode (autowire="byName"), and then finds the bean with the same attribute name in the Spring container for association according to its attributes

byType

Automatic assembly by the data type of the attribute. The Spring container sees that the bean adopts the automatic assembly byType mode (autowire="byType"), and then finds the bean with the same attribute type in the Spring container for association according to the attribute type. If there is more than one such bean, an exception will be thrown.

constructor

Similar to byType, but this type applies to constructor parameter types. If there is no bean of the constructor parameter type in the container, a fatal error will occur

      Next, we use a case to demonstrate the use of byName and byType:

      (1) Create Staff and Department classes respectively

public class Staff {
    private String name;
    private Department department;

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

    public void setDepartment(Department department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Staff{" +
                "name='" + name + '\'' +
                ", department=" + department +
                '}';
    }
}
public class Department {
    private String dName;

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

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

       (2) Configure in bean.xml

    <!--  手动装配  -->
    <bean id="staff1" class="com.yht.example3.entity.Staff">
        <property name="name" value="张三"></property>
        <property name="department" ref="department"></property>
    </bean>
    <bean id="department" class="com.yht.example3.entity.Department">
        <property name="dName" value="技术部"></property>
    </bean>
    <!--  自动装配 byName -->
    <bean id="staff2" class="com.yht.example3.entity.Staff" autowire="byName">
        <property name="name" value="李四"></property>
    </bean>
    <!--  自动装配 byType -->
    <bean id="staff3" class="com.yht.example3.entity.Staff" autowire="byType">
        <property name="name" value="王五"></property>
    </bean>

      (3) Perform unit testing

    @Test
    public void testAutowired(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Staff staff1 = context.getBean("staff1", Staff.class);//手动装配
        Staff staff2 = context.getBean("staff2", Staff.class);//自动装配 byName
        Staff staff3 = context.getBean("staff3", Staff.class);//自动装配 byType
        System.out.println(staff1);
        System.out.println(staff2);
        System.out.println(staff3);
    }

      The execution results are as follows:

      Notes on byType:

       If byType is used for automatic assembly, there can only be one instance object of the same type in bean.xml, otherwise an error will be reported.

Solution: When multiple bean objects of the same type are found, one of them can be set with the primary attribute as the preferred object. As follows :

    <bean id="department2" class="com.yht.example3.entity.Department"  primary="true">
        <property name="dName" value="财务部"></property>
    </bean>

      The execution results are as follows:

 

      It should be noted that even if the primary is used, there will still be error messages in bean.xml. So in this case, try to exclude useless bean objects.

 Second, the external properties file

      Usually when encountering some public data or global data, it will be configured in an external file, and then the content in the external file will be read in xml. Here, we take the configuration of the database as an example:

      First, introduce the Druid connection pool dependency jar package

    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.22</version>
    </dependency>

1. Direct configuration method

    <!--直接配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/test"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

2. The way of external files

      (1) Create an external properties file with the suffix properties and write database information 

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.userName=root
jdbc.password=root

      (2) Introduce context name space

     <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!--引入context名称空间-->

    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.userName}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

</beans>

 

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/112777293