XML-Based Injection in Spring

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>

参考:
XML-Based Injection in Spring

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值