Enjoying this Java & Spring tutorial?
Subscribe to Ram N Java on YouTubeIntroduction
In Spring Framework, constructor-based dependency injection allows you to create immutable, thread-safe beans that have all required properties supplied during instantiation. A common requirement in Java applications is injecting collections such as java.util.List.
In this guide, you will learn how to configure and inject a List collection into your Java class through its constructor using Spring XML bean definitions.
1. Create the Java Bean Class
First, create a bean class (for example, FruitShop) containing a List<String> property and define a constructor that initializes it:
import java.util.List;
public class FruitShop {
private String shopName;
private List<String> fruitNames;
public FruitShop(String shopName, List<String> fruitNames) {
this.shopName = shopName;
this.fruitNames = fruitNames;
}
public void displayFruitShopInfo() {
System.out.println("Shop Name: " + shopName);
System.out.println("Available Fruits:");
for (String fruit : fruitNames) {
System.out.println(" - " + fruit);
}
}
}
2. Configure Spring XML with <list>
In your Spring XML configuration file (applicationContext.xml), define the bean and pass the collection values inside <constructor-arg> using the <list> and <value> elements:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="fruitShop" class="FruitShop">
<constructor-arg value="Metro Fruit Center" />
<constructor-arg>
<list>
<value>Apple</value>
<value>Mango</value>
<value>Orange</value>
<value>Strawberry</value>
</list>
</constructor-arg>
</bean>
</beans>
3. Run and Verify the Output
Load the Spring application context using ClassPathXmlApplicationContext and test the injected list:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
FruitShop shop = (FruitShop) context.getBean("fruitShop");
shop.displayFruitShopInfo();
}
}
Watch More Spring Tutorials
Click here to watch on Youtube:
https://www.youtube.com/watch?v=hZHV0oB1OVk&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge:
| How to Inject List Collection using Spring dependency injection by constructor? | Spring Tutorial |
| How to Inject List Collection using Spring dependency injection by constructor? | Spring Tutorial |
| How to Inject List Collection using Spring dependency injection by constructor? | Spring Tutorial |