1. Introduction
In this basic tutorial, we’ll learn how to do simple XML-based bean configuration with the Spring Framework.
2. Overview
Let’s start by adding Spring’s library dependency in the pom.xml:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
3. Dependency Injection – an Overview
public class IndexApp {
private IService service;
// standard constructors/getters/setters
}
public interface IService {
public String serve();
}
public class IndexService implements IService {
@Override
public String serve() {
return "Hello World";
}
}
4.1. Using Properties
<bean id="indexService" class="com.di.spring.IndexService" />
<bean id="indexApp" class="com.di.spring.IndexApp" >
<property name="service" ref="indexService" />
</bean>
we’re creating an instance of IndexService
and assigning it an id. By default, the bean is a singleton. Also, we’re creating an instance of IndexApp
. Within this bean, we’re injecting the other bean using setter method
.
4.2. Using Constructor
Instead of injecting a bean via the setter method, we can inject the dependency using the constructor
<bean id="indexApp" class="com.di.spring.IndexApp">
<constructor-arg ref="indexService" />
</bean>
4.3. Using Static Factory
<bean id="messageService" class="com.di.spring.StaticServiceFactory"
factory-method="getService">
<constructor-arg value="1" />
</bean>
<bean id="indexApp" class="com.di.spring.IndexApp">
<property name="service" ref="messageService" />
</bean>
In the above example, we’re calling the static getService
method using factory-method to create a bean with id messageService
which we inject into IndexApp
.
4.4. Using Factory Method
<bean id="indexServiceFactory" class="com.di.spring.InstanceServiceFactory" />
<bean id="messageService" class="com.di.spring.InstanceServiceFactory"
factory-method="getService" factory-bean="indexServiceFactory">
<constructor-arg value="1" />
</bean>
<bean id="indexApp" class="com.di.spring.IndexApp">
<property name="service" ref="messageService" />
</bean>