Spring project autowiring & collection injection

1. Automatic configuration

1.1 What is dependency autowiring?

  • The process that the IoC container automatically finds and injects into the bean according to the resources the bean depends on is called autowiring

1.2 What are the automatic assembly methods?

  • By Type (Common)
  • by name
  • By construction method
  • Autowiring is not enabled

1.3 Prepare the next case environment

  • Create a Maven project
  • pom.xml add dependencies
  • Add spring configuration file under resources

The structure of the project is as follows:

(1) Add UserDao, UserDaoImpl, UserService and UserServiceImpl classes to the project

public interface UserDao {
    public void select();
}
public class UserDaoImpl implements UserDao {

    private String userName;
    private Integer userAge;

    public void select() {
        System.out.println("UserDao select, running ......");
    }
}
public interface UserService {
    public void select();
}
public class UserServiceImpl implements UserService {

    private UserDao userDao;

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

    public void select() {
        System.out.println("UserService select, running ......");
        userDao.select();
    }
}

(2) The configuration file of spring is provided under resources

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="userDao" class="com.dcxuexi.dao.impl.UserDaoImpl" />
    <bean id="userService" class="com.dcxuexi.service.impl.UserServiceImpl" >
        <property name="userDao" ref="userDao" />
    </bean>
</beans>

(3) Write the AppForAutoware running class, load Spring's IOC container, and obtain the corresponding bean object from it

public class SpringAnto {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.select();
    }
}

1.4 Complete the configuration of autowiring

Next, complete the learning of automatic assembly in the above environment:
Autowiring only needs to modify the applicationContext.xml configuration file:
(1) Delete the <property> tag
(2) Add the autowire attribute to the <bean> tag
First, let's implement the configuration injected by type

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="com.dcxuexi.dao.impl.UserDaoImpl" />
    <!--autowire Properties: Turn on autowiring, usually use by-type wiring-->
    <bean id="userService" class="com.dcxuexi.service.impl.UserServiceImpl"  autowire="byType" />
    
</beans>

Precautions:

  • The setter method of the corresponding property in the class that needs to inject the property cannot be omitted
  • The injected object must be managed by Spring's IOC container
  • According to the type, if multiple objects are found in Spring's IOC container, NoUniqueBeanDefinitionException will be reported

A type has multiple objects in the IOC, and if you want to inject successfully, you need to inject by name. The configuration method is:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="com.dcxuexi.dao.impl.UserDaoImpl" />
    <!--autowire Properties: Turn on autowiring, usually use by-type wiring-->
    <bean id="userService" class="com.dcxuexi.service.impl.UserServiceImpl"  autowire="byName" />

</beans>

Precautions:

  • What does the name in injection by name refer to?
    • userDao is private ly modified, and external classes cannot directly method
    • External classes can only be accessed through the property's set method
    • For external classes, the method name of setUserDao, after removing set, the first letter in lowercase is its attribute name
      • Why is the first letter of set removed in lowercase?
      • This rule is the default rule generated by the set method. The generation of the set method is the method name formed by capitalizing the first letter of the property name and adding set before it.
    • So injecting by name is actually related to the corresponding set method, but if the name is based on the standard, the attribute name and the name corresponding to the set are the same
  • If you find the corresponding bean object according to the name, if you can't find it, inject Null
  • When a certain type has multiple objects in the IOC container, according to the name injection, only the bean object corresponding to the specified name will be found, and no error will be reported.

After the introduction of the two methods, the injection by type will be used more in the future.
Finally, for dependency injection, there are some other configuration features to be aware of:

  1. Autowiring is used for reference type dependency injection and cannot operate on simple types
  2. When using assembly by type (byType), you must ensure that bean s of the same type in the container are unique. It is recommended to use
  3. When using assembly by name (byName), you must ensure that a bean with the specified name in the container is used. The dependent variable name is coupled with the configuration, which is not recommended.
  4. The priority of autowiring is lower than that of setter injection and constructor injection, and the autowiring configuration is invalid when it occurs at the same time

2. Collection injection

We have been able to complete the injection of introduced data types and simple data types before, but there is also a data type collection, which can be loaded with both simple data types and reference data types. For collections, how to inject in Spring?
Let’s review first, what are the common types of collections?

  • array
  • List
  • Set
  • Map
  • Properties

How to implement injection for different collection types?

2.1 Environmental preparation

  • Create a Maven project
  • pom.xml add dependencies
  • Add spring's configuration file applicationContext.xml under resources

The structure of the project is as follows:

(1) Add UserDao and UserDaoImpl classes to the project

public interface UserDao {
    public void select();
}
public class UserDaoImpl implements UserDao {

    private int[] array;
    private Set<String> set;
    private List<String> list;
    private Map<String,String> map;
    private Properties properties;

    public void setArray(int[] array) {
        this.array = array;
    }

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

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

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

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public void select() {
        System.out.println("UserDao select, running .....");
        System.out.println("array = " + Arrays.toString(array));
        System.out.println("set = " + set);
        System.out.println("list = " + list);
        System.out.println("map = " + map);
        System.out.println("properties = "+ properties);

    }
}

(2) The configuration file of spring is provided under resources, applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userDao" class="com.dcxuexi.dao.impl.UserDaoImpl" />

</beans>

(3) Write a SpringCollection runtime class, load Spring's IOC container, and obtain the corresponding bean object from it

public class SpringCollection {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) context.getBean("userDao");
        userDao.select();
    }
}

Next, complete the learning of collection injection in the above environment:
All the following configuration methods are used for injection in the bean tag of userDao

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userDao" class="com.dcxuexi.dao.impl.UserDaoImpl" >
        
    </bean>

</beans>

2.2 Injecting array type data

        <property name="array">
            <array>
                <value>1</value>
                <value>2</value>
                <value>3</value>
            </array>
        </property>

2.3 Injecting List type data

        <property name="list">
            <list>
                <value>blue</value>
                <value>red</value>
                <value>green</value>
            </list>
        </property>

2.4 Injecting Set type data

        <property name="set">
            <set>
                <value>zhangsan</value>
                <value>lisi</value>
                <value>wangwu</value>
            </set>
        </property>

2.5 Injecting Map type data

        <property name="map">
            <map>
                <entry key="name" value="xiaochuang" />
                <entry key="age" value="20" />
                <entry key="address" value="shanghai" />
            </map>
        </property>

2.6 Injecting Properties type data

        <property name="properties">
            <props>
                <prop key="ip">192.168.1.110</prop>
                <prop key="port">18080</prop>
            </props>
        </property>

Configuration for full injection

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userDao" class="com.dcxuexi.dao.impl.UserDaoImpl" >
        <property name="array">
            <array>
                <value>1</value>
                <value>2</value>
                <value>3</value>
            </array>
        </property>
        <property name="set">
            <set>
                <value>zhangsan</value>
                <value>lisi</value>
                <value>wangwu</value>
            </set>
        </property>
        <property name="list">
            <list>
                <value>blue</value>
                <value>red</value>
                <value>green</value>
            </list>
        </property>
        <property name="map">
            <map>
                <entry key="name" value="xiaochuang" />
                <entry key="age" value="20" />
                <entry key="address" value="shanghai" />
            </map>
        </property>
        <property name="properties">
            <props>
                <prop key="ip">192.168.1.110</prop>
                <prop key="port">18080</prop>
            </props>
        </property>
    </bean>

</beans>

After the configuration is complete, run the following to see the results:

illustrate:

  • The property tag indicates setter injection, and the constructor injection can also write <array>, <list>, <set>, <map>, <props> tags inside the constructor-arg tag
  • The bottom layer of List is also implemented through arrays, so <list> and <array> tags can be mixed
  • To add a reference type to the collection, you only need to change the <value> tag to a <ref> tag, which is rarely used.

Welcome to the public account "Forge ahead" for communication

Forge ahead together, learn together, progress together, and move forward together.


Tags: Java Spring Back-end

Posted by renu on Mon, 24 Oct 2022 08:38:13 +0300