Showing posts with label String Array. Show all posts
Showing posts with label String Array. Show all posts

Sunday, 1 July 2018

How to Inject Array of String using Spring dependency injection by Setter method? | Spring Tutorial

Enjoying This Tutorial?

Subscribe to Ram N Java for high-quality, practical Java and Spring tutorials!

SUBSCRIBE NOW

Introduction

In Spring Framework applications, configuring collections and arrays is a fundamental requirement. Whether managing a list of role names, configuration paths, or categories, Spring makes it straightforward to inject an array of strings (String[]) into a bean using setter-based dependency injection.

Why Use Setter Injection for String Arrays?

  • Built-in Conversion: Spring’s IoC container seamlessly parses XML <array> or <list> definitions and converts them into a Java String[] array.
  • Clean Property Configuration: Using the <value> sub-element inside <array> allows you to specify string values cleanly without custom parsing logic.
  • Flexibility: Setter-based injection allows collection properties to be optional or reconfigured easily during development and testing.

Step-by-Step Code Example

Here is an example demonstrating an Employee class receiving an array of programming skills via setter dependency injection:

1. The Java Model Class

package com.ram.model;

import java.util.Arrays;

public class Employee {
    private String name;
    private String[] skills;

    public void setName(String name) {
        this.name = name;
    }

    // Setter method for injecting String array
    public void setSkills(String[] skills) {
        this.skills = skills;
    }

    public void display() {
        System.out.println("Employee Name: " + name);
        System.out.println("Skills: " + Arrays.toString(skills));
    }
}

2. Configuring applicationContext.xml

Use the <property> element along with the nested <array> and <value> tags:

<bean id="employee" class="com.ram.model.Employee">
    <property name="name" value="Ram" />
    <property name="skills">
        <array>
            <value>Java</value>
            <value>Spring Framework</value>
            <value>Hibernate</value>
            <value>Microservices</value>
        </array>
    </property>
</bean>

3. Loading and Executing with ApplicationContext

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

Employee emp = (Employee) context.getBean("employee");
emp.display();

Key Takeaway

Spring simplifies injecting string arrays by using standard <array> elements inside property tags. This eliminates hardcoded values and keeps collection configurations neatly centralized in XML.

Tutorials