Skip to content

Spring Dependency Injection XML#

Constructor Injection Type With XML#

  • In this approach, the DI will be injected with the help of constructors. Now to set the DI of a bean as Constructor Injection Type in XML bean-configuration file, we have to use the <constructor-arg> tag in the bean-config.
applicationContext.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?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: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">

    <bean id="englishExaminationService"
          class="com.spring.core.spring.dependency.injection.EnglishExaminationService">
    </bean>

    <bean id="englishCoach"
          class="com.spring.core.spring.dependency.injection.EnglishCoach">
        <constructor-arg ref="englishExaminationService"/>
    </bean>

</beans>
  • To use the Constructor Injection in our Spring, we should follow these steps:

    • Define the dependency interface and class
    • Create a constructor in our class for injections
    • Configure the dependency injection in Spring config file.
  • So let's take an example for the Constructor Injection Type as following steps below.

Dependency#

  • Like we took an example with Spring Inversion Of Control, we will need to add the dependency spring-context for creating the Spring Container and configuring Constructor Injection Type.
pom.xml
1
2
3
4
5
6
7
8
9
....  

<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-context</artifactId>  
    <version>5.3.24</version>  
</dependency>

....

Define the dependency interface and class#

  • So now, let's create 2 interfaces Coach and ExanminationService and they will be implemented by 2 java classes EnglishCoach and EnghlishExaminationService correspondingly. Then the class EnglishCoach will need to use ExanminationService as a dependency for it's method.

 #zoom

  • So, firstly let's create ExaminationService interface and EnglishExaminationService implementation class as below.
ExaminationService.java
1
2
3
4
5
6
7
package com.spring.core.spring.dependency.injection;

public interface ExaminationService {

    public String getExamination();

}
EnglishExaminationService.java
1
2
3
4
5
6
7
8
9
package com.spring.core.spring.dependency.injection;

public class EnglishExaminationService implements ExaminationService {

    @Override
    public String getExamination() {
        return "Focus and take English examination in 3 hours";
    }
}
  • Then let's create the Coach interface and EnglishCoach implementation class as below.
Coach.java
1
2
3
4
5
6
7
8
9
package com.spring.core.spring.dependency.injection;

public interface Coach {

    public String getDailyHomeWork();

    public String getExamination();

}
EnglishCoach.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package com.spring.core.spring.dependency.injection;  

public class EnglishCoach implements Coach {  

    @Override  
    public String getDailyHomeWork() {  
        return "Spend 1 hour to practise Speaking Skill!";  
    }  

    @Override  
    public String getExamination() {  
        return null; 
    }  

}

Create a constructor in our class for injections#

  • Now, in the EnglishCoach, let's create a constructor and inject the ExaminationService as below.
EnglishCoach.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package com.spring.core.spring.dependency.injection;

public class EnglishCoach implements Coach {

    private final ExaminationService examinationService;

    public EnglishCoach(ExaminationService examinationService) {
        this.examinationService = examinationService;
    }

    @Override
    public String getDailyHomeWork() {
        return "Spend 1 hour to practise Speaking Skill!";
    }

    @Override
    public String getExamination() {
        return this.examinationService.getExamination();
    }

}
  • As you can see, in the constructor of EnglishCoach class we will inject the ExaminationService and use it for getExamination() method.

Configure the DI in Spring config file#

  • Now, let's create the XML configuration file applicationContext.xml in our resources folder and put the configuration as below.
applicationContext.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?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: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">

    <bean id="englishExaminationService"
          class="com.spring.core.spring.dependency.injection.EnglishExaminationService">
    </bean>

    <bean id="englishCoach"
          class="com.spring.core.spring.dependency.injection.EnglishCoach">
        <constructor-arg ref="englishExaminationService"/>
    </bean>

</beans>
  • As you can see, for the bean englishCoach, we will inject the bean englishExaminationService by using tag constructor-arg for constructor injection type.

Testing#

  • So now, let's create the main class SpringApplication and then we will create the container with xml configuration file and get beans for using.
SpringApplication.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package com.spring.core.spring.dependency.injection;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringApplication {
    public static void main(String[] args) {

        //create Spring Container with configuration file
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //Get bean from container
        Coach englishCoach = context.getBean("englishCoach", Coach.class);

        //use bean
        System.out.println(englishCoach.getDailyHomeWork());
        System.out.println(englishCoach.getExamination());

        //close container
        context.close();
    }
}
  • So when we run our application, we expect that we will get the information from the EnglishExaminationService because we injected it into the EnglishCoach by using constructor type in xml configuration.
  • The successful result when run the application is show as below.
1
2
3
4
Spend 1 hour to practise Speaking Skill!
Focus and take English examination in 3 hours

Process finished with exit code 0

Setter Injection Type With XML#

  • This is the simpler of the two DI methods. In this approach, the DI will be injected with the help of setter and/or getter methods. Now to set the DI as setter dependency injection in a bean we have to use the <property> tag in the bean-config.
  • To use the Setter Injection in our Spring, we should follow these steps:

    • Create setter methods in our class for injections
    • Configure the dependency injection in Spring config file.
  • So let's take an example for the Constructor Injection Type as following steps below.

Create Setter Methods In Our Class For Injections#

  • Now, we will extend the example that we made before in Constructor Injection Type with new interface and implementation class. Let's see the diagram below.

 #zoom

  • So let's create class HistoryExaminationService which will implement ExaminationService interface as below
HistoryExaminationService.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package com.spring.core.spring.dependency.injection;

public class HistoryExaminationService implements ExaminationService {

    @Override
    public String getExamination() {
        return "Focus and take History examination in 3 hours";
    }

}
  • Now, let's create class HistoryCoach which will implement Coach interface as below.
HistoryCoach.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package com.spring.core.spring.dependency.injection;

public class HistoryCoach implements Coach {

    private ExaminationService examinationService;

    public void setExaminationService(ExaminationService examinationService) {
        this.examinationService = examinationService;
    }

    @Override
    public String getDailyHomeWork() {
        return "Spend 20 minutes to read history books";
    }

    @Override
    public String getExamination() {
        return this.examinationService.getExamination();
    }

}
  • As you can see, in the HistoryCoach we will create a setter method for ExaminationService.

Configure The DI in Spring Config File#

  • Next, let's add more configuration in the applicationContext.xml in our resources folder.
applicationContext.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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: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">

    <bean id="englishExaminationService"
          class="com.spring.core.spring.dependency.injection.EnglishExaminationService">
    </bean>

    <bean id="englishCoach"
          class="com.spring.core.spring.dependency.injection.EnglishCoach">
        <constructor-arg ref="englishExaminationService"/>
    </bean>

    <bean id="historyCoach"
          class="com.spring.core.spring.dependency.injection.HistoryCoach">
        <property name="examinationService" ref="historyExaminationService"/>
    </bean>

    <bean id="historyExaminationService"
          class="com.spring.core.spring.dependency.injection.HistoryExaminationService">
    </bean>

</beans>
  • As you can see, for the bean historyCoach, we will inject the bean historyExaminationService by using property tag with name and ref attributes. In which:
    • name will contain the name of setter method in the historyCoach without set and the first letter is lower case (examinationService).
    • ref will contain the bean-id of the bean that we want to inject, in this case it is historyExaminationService.

Testing#

  • Finally, let's update our SpringApplication for getting and using bean historyCoach as below.
SpringApplication.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.spring.core.spring.dependency.injection;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringApplication {
    public static void main(String[] args) {

        //create Spring Container with configuration file
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //Get bean from container
        Coach englishCoach = context.getBean("englishCoach", Coach.class);
        Coach historyCoach = context.getBean("historyCoach", Coach.class);

        //use bean
        System.out.println(englishCoach.getDailyHomeWork());
        System.out.println(englishCoach.getExamination());

        System.out.println(historyCoach.getDailyHomeWork());
        System.out.println(historyCoach.getExamination());

        //close container
        context.close();
    }
}
  • Then when our application run, we will see the successful result as below. We can see the information of historyExaminationService which is injected and used by historyCoach.
1
2
3
4
5
6
Spend 1 hour to practise Speaking Skill!
Focus and take English examination in 3 hours
Spend 20 minutes to read history books
Focus and take History examination in 3 hours

Process finished with exit code 0

Inject Values From Properties File With XML#

  • From the section above, we learnt how to use Setter Injection Type for DI. In this section, we will continue to use it for injecting values from the properties files in our resources folders.

 #zoom

  • To use the Setter Injection for injecting values from the properties file in our Spring, we should follow these steps:
    • Create Properties File.
    • Load Properties File in Spring config file
    • Reference values from Properties file

Prepare#

  • So, Let's continue with the example that we did from the last section Setter Injection Type. In the HistoryCoach and EnglishCoach classes, we will set new attribute teamEmail with getter and setter methods for them as below.
EnglishCoach.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.spring.core.spring.dependency.injection;

public class EnglishCoach implements Coach {

    private final ExaminationService examinationService;
    private String teamEmail;

    public EnglishCoach(ExaminationService examinationService) {
        this.examinationService = examinationService;
    }

    @Override
    public String getDailyHomeWork() {
        return "Spend 1 hour to practise Speaking Skill!";
    }

    @Override
    public String getExamination() {
        return this.examinationService.getExamination();
    }

    public ExaminationService getExaminationService() {
        return examinationService;
    }

    public String getTeamEmail() {
        return teamEmail;
    }

    public void setTeamEmail(String teamEmail) {
        this.teamEmail = teamEmail;
    }
}
HistoryCoach.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.spring.core.spring.dependency.injection;

public class HistoryCoach implements Coach {

    private String teamEmail;
    private ExaminationService examinationService;

    public void setExaminationService(ExaminationService examinationService) {
        this.examinationService = examinationService;
    }

    @Override
    public String getDailyHomeWork() {
        return "Spend 20 minutes to read history books";
    }

    @Override
    public String getExamination() {
        return this.examinationService.getExamination();
    }

    public String getTeamEmail() {
        return teamEmail;
    }

    public void setTeamEmail(String teamEmail) {
        this.teamEmail = teamEmail;
    }
}

Create Properties File#

  • Let's create a properties file with name application.properties in our project resources as below.
application.properties
1
2
coach.team.english.email=englishCoach@example.com  
coach.team.history.email=historyCoach@example.com
  • As you can see in the application.properties we have 2 variable with name and value.
    • name is the left part of =
    • value is the right part of =

Load Properties File In Spring Config File#

  • To load variables from application.properties, we just need to add the tag context:property-placeholder with location attribute as below into applicationContext.xml.
applicationContext.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?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: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:property-placeholder location="classpath:application.properties"/>

    <bean id="englishExaminationService"
          class="com.spring.core.spring.dependency.injection.EnglishExaminationService">
    </bean>

    <bean id="englishCoach"
          class="com.spring.core.spring.dependency.injection.EnglishCoach">
        <constructor-arg ref="englishExaminationService"/>
    </bean>

    <bean id="historyCoach"
          class="com.spring.core.spring.dependency.injection.HistoryCoach">
        <property name="examinationService" ref="historyExaminationService"/>
    </bean>

    <bean id="historyExaminationService"
          class="com.spring.core.spring.dependency.injection.HistoryExaminationService">
    </bean>

</beans>
  • In which, the value of attribute location in context:property-placeholder tag should be start with classpath: then the properties's file name will be put after.

Reference Values From Properties File#

  • Now, to reference values from the application.properties file into HistoryCoach and EnglishCoach beans, we will use property tag with name and value attributes. In which:
    • name will contain the name of setter method in the historyCoach and EnglishCoach without set and the first letter is lower case (teamEmail).
    • value will contain the name of variable that we defined in the application.properties file (coach.team.english.email and coach.team.history.email) and these names have to be put in the syntax ${<variable name>}. Ex: ${coach.team.english.email}. With this syntax Spring will load the value of that variable for you directly.
applicationContext.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?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: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:property-placeholder location="classpath:application.properties"/>

    <bean id="englishExaminationService"
          class="com.spring.core.spring.dependency.injection.EnglishExaminationService">
    </bean>

    <bean id="englishCoach"
          class="com.spring.core.spring.dependency.injection.EnglishCoach">
        <constructor-arg ref="englishExaminationService"/>
        <property name="teamEmail" value="${coach.team.english.email}"/>
    </bean>

    <bean id="historyCoach"
          class="com.spring.core.spring.dependency.injection.HistoryCoach">
        <property name="examinationService" ref="historyExaminationService"/>
        <property name="teamEmail" value="${coach.team.history.email}"/>
    </bean>

    <bean id="historyExaminationService"
          class="com.spring.core.spring.dependency.injection.HistoryExaminationService">
    </bean>

</beans>

Testing#

  • Finally, let's update our SpringApplication for getting and using bean EnglishCoach and historyCoach with injected values from the application.properties file as below.
SpringApplication.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.spring.core.spring.dependency.injection;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringApplication {
    public static void main(String[] args) {

        //create Spring Container with configuration file
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //Get bean from container
        Coach englishCoach = context.getBean("englishCoach", Coach.class);
        Coach historyCoach = context.getBean("historyCoach", Coach.class);

        EnglishCoach englishCoachDetail = context.getBean("englishCoach", EnglishCoach.class);
        HistoryCoach historyCoachDetail = context.getBean("historyCoach", HistoryCoach.class);

        //use bean
        System.out.println(englishCoach.getDailyHomeWork());
        System.out.println(englishCoach.getExamination());

        System.out.println(historyCoach.getDailyHomeWork());
        System.out.println(historyCoach.getExamination());

        System.out.println(englishCoachDetail.getTeamEmail());
        System.out.println(historyCoachDetail.getTeamEmail());

        //close container
        context.close();
    }
}
  • Then when our application run, we will see the successful result as below. We can see the values in the application.properties which are injected and used by EnglishCoach and HistoryCoach.
1
2
3
4
5
6
7
8
Spend 1 hour to practise Speaking Skill!
Focus and take English examination in 3 hours
Spend 20 minutes to read history books
Focus and take History examination in 3 hours
englishCoach@example.com
historyCoach@example.com

Process finished with exit code 0

See Also#

References#