SoFunction
Updated on 2025-03-04

Spring DI Dependency Injection Practical Tutorial

1 Overview

  • rely
    • Object A has a reference to object B, and some operations need to be completed using object B.
    • Object A depends on B
  • injection
    • Assigning values ​​to B objects that are dependent on by object A is called injection

2 Injection method

1. Set injection

2. Structural injection

3. Automatic injection

4. P namespace injection

3 Data types that can be injected

Basic Type

Custom Objects

Container Type

Array

​ Collection

​ Map

​ Properties

4 set injection

  • When creating an object, the Spring factory will call the set method to assign values ​​to the properties in the object.
  • If the property in an object does not add the set method, an error will be reported when using property assignment.
Error:(11, 13) java: Symbol not found
  symbol:   method setId(int)
  Location: Variable of type user
import ;
@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private String addr;
    private String info;
}
<!--  definitionuser  -->
<bean  class="">
    <property name="id" value="100111"></property>
    <property name="username" value="Guan Yu"></property>
    <property name="info" value="Guan Yu, who sells miscellaneous grains"></property>
</bean>

5 Constructor Injection

Injecting properties through the object's constructor

<constructor-arg name="id" value="100110"></constructor-arg>
package ;
public class Hero {
    private Integer id;
    private String username;
    private String password;
    private String addr;
    private String info;
    public Hero() {
    }
    public Hero(String username, String password) {
         = username;
         = password;
    }
    public Hero(Integer id, String username) {
         = id;
         = username;
    }
    public Hero(Integer id, String username, String password, String addr, String info) {
         = id;
         = username;
         = password;
         = addr;
         = info;
    }
    @Override
    public String toString() {
        return "Hero{" +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", addr='" + addr + '\'' +
                ", info='" + info + '\'' +
                '}';
    }
}
    &lt;!--  definitionHero  --&gt;
    &lt;bean  class=""&gt;
        &lt;constructor-arg name="id" value="100110"&gt;&lt;/constructor-arg&gt;
        &lt;constructor-arg name="username" value="Liu Bei"&gt;&lt;/constructor-arg&gt;
    &lt;/bean&gt;
    &lt;bean  class=""&gt;
        &lt;constructor-arg name="username" value="Zhao Yun"&gt;&lt;/constructor-arg&gt;
        &lt;constructor-arg name="password" value="zhao"&gt;&lt;/constructor-arg&gt;
    &lt;/bean&gt;

6 Automatic injection

How to declare autowire in bean tag

Spring framework will find data that matches parameters in the container for injection

  • byType
  • byName
package ;
import ;
import ;
import ;
public class HeroServiceImpl implements HeroService {
    private HeroDao heroDao;
    public void setHeroDao(HeroDao heroDao) {
         = heroDao;
    }
    @Override
    public Hero queryHeroById(Integer id) {
        return (id);
    }
}
    <!--  heroService  -->
    <bean  class="" autowire="byType"></bean>
    <!--  heroService  -->
    <bean  class="" autowire="byName"></bean>
    @Test
    public void getHero01(){
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("");
        HeroService heroService = ("heroService01",);
        Hero hero = (10010);
        (hero);
    }
    @Test
    public void getHero02(){
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("");
        HeroService heroService = ("heroService02",);
        Hero hero = (1001111);
        (hero);
    }

Automatic injection or set injection

7p namespace injection

  • Use p as the prefix of the attribute to call the attribute to perform the copy operation
  • In essence, it is still used to assign values ​​using the set method

xmlns:p=“/schema/p”

    &lt;!--  stu  --&gt;
    &lt;bean  class="" p: p:username="Zhang San"&gt;&lt;/bean&gt;
    @Test
    public void getStu(){
        ClassPathXmlApplicationContext ioc = 
        	new ClassPathXmlApplicationContext("");
        Stu stu = ();
        (stu);
    }

8 Data source injection

  • Injecting Druid data source using Spring factory
  • rely
        <dependency>
            <groupId></groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

Declare references to data sources in dao

package ;
import ;
import ;
import ;
import ;
public class HeroDaoImpl implements HeroDao {
    private DruidDataSource dataSource;
    public DruidDataSource getDataSource() {
        return dataSource;
    }
    public void setDataSource(DruidDataSource dataSource) {
         = dataSource;
    }
    @Override
    public Hero selectHeroById(Integer id) {
        try {
            (());
        } catch (SQLException e) {
            ();
        }
        Hero hero = new Hero();
        (id);
        return hero;
    }
}

Configuration

      &lt;!--  Introduce external configuration files  --&gt;
    &lt;context:property-placeholder location="classpath:"&gt;&lt;/context:property-placeholder&gt;
  &lt;!-- Configure data source   --&gt;
    &lt;bean  class=""&gt;
        &lt;property name="driverClassName" value="${}"&gt;&lt;/property&gt;
        &lt;property name="url" value="${}"&gt;&lt;/property&gt;
        &lt;property name="username" value="${}"&gt;&lt;/property&gt;
        &lt;property name="password" value="${}"&gt;&lt;/property&gt;
    &lt;/bean&gt;
    &lt;!--  heroDao  --&gt;
    &lt;bean  class=""&gt;
        &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt;
    &lt;/bean&gt;

test

package ;
import ;
import ;
import ;
import ;
import ;
public class TestHeroDao {
    @Test
    public void getHeroDao() {
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("");
        HeroDao heroDao = ();
        Hero hero = (222);
    }
}

4.9 Container type data injection

package ;
import ;
import ;
import ;
@Data
public class Person {
    private Integer id;
    private String username;
    private String gender;
    private String info;
    private String[] hobby;
    private List<String> friend;
    private Map<String,String> phones;
}
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xmlns:p="/schema/p"
       xmlns:context="/schema/context"
       xsi:schemaLocation="/schema/beans
       /schema/beans/
       /schema/context
       /schema/context/"&gt;
    &lt;!--  personBasic attribute injection  --&gt;
    &lt;bean  class=""&gt;
        &lt;property name="id" value="100100"&gt;&lt;/property&gt;
        &lt;property name="username" value="Song Jiang"&gt;&lt;/property&gt;
        &lt;property name="gender" value="male"&gt;&lt;/property&gt;
        &lt;property name="info" value="Liangshantou"&gt;&lt;/property&gt;
    &lt;/bean&gt;
    &lt;!--  Inject an array  --&gt;
    &lt;bean  class=""&gt;
        &lt;property name="hobby"&gt;
            &lt;array&gt;
                &lt;value&gt;basketball&lt;/value&gt;
                &lt;value&gt;football&lt;/value&gt;
                &lt;value&gt;table tennis&lt;/value&gt;
            &lt;/array&gt;
        &lt;/property&gt;
    &lt;/bean&gt;
    &lt;bean  class=""&gt;
        &lt;property name="friend"&gt;
            &lt;list&gt;
                &lt;value&gt;Chao Gai&lt;/value&gt;
                &lt;value&gt;Hu Sanniang&lt;/value&gt;
                &lt;value&gt;Wang Po&lt;/value&gt;
                &lt;value&gt;Wu Song&lt;/value&gt;
            &lt;/list&gt;
        &lt;/property&gt;
    &lt;/bean&gt;
    &lt;!--  mapparameter  --&gt;
    &lt;bean  class=""&gt;
        &lt;property name="phones"&gt;
            &lt;map&gt;
                &lt;entry key="Lu Zhishen" value="10010"&gt;&lt;/entry&gt;
                &lt;entry key="Lin Chong" value="10086"&gt;&lt;/entry&gt;
                &lt;entry key="Li Kui" value="10000"&gt;&lt;/entry&gt;
                &lt;entry key="Farewell" value="100000"&gt;&lt;/entry&gt;
            &lt;/map&gt;
        &lt;/property&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
package ;
import ;
import ;
import ;
public class TestPerson {
    @Test
    public void getPerson01(){
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("");
        Person person01 = ("person01", );
        (person01);
    }
    @Test
    public void getPerson02(){
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("");
        Person person02 = ("person02", );
        (person02);
    }
    @Test
    public void getPerson03(){
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("");
        Person person03 = ("person03", );
        (person03);
    }
    @Test
    public void getPerson04(){
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("");
        Person person04 = ("person04", );
        (person04);
    }
}

This is all about this article about SpringDI dependency injection. For more related SpringDI dependency injection content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!