Enjoying this Java & Spring tutorial?
Subscribe to Ram N Java on YouTubeIntroduction
In Spring Framework, Constructor Injection is one of the most fundamental ways to pass required configuration data into your beans upon instantiation. When working with literal text values like names, identifiers, or URLs, passing a String directly through the constructor guarantees that the bean is initialized with all its required state.
In this beginner-friendly tutorial, you will learn how to configure Spring XML to inject a simple String value into a Java class using constructor-based dependency injection.
1. Create the Java Bean Class
First, create a Java class (for instance, Employee) that has a String member variable and a constructor that accepts this parameter:
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public void displayEmployeeInfo() {
System.out.println("Employee Name: " + name);
}
}
2. Configure Spring XML with <constructor-arg>
In your Spring configuration file (applicationContext.xml), define the bean and pass the String value using the <constructor-arg> element. You can optionally specify type="java.lang.String" for clarity:
<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="employeeBean" class="Employee">
<constructor-arg type="java.lang.String" value="Peter" />
</bean>
</beans>
3. Run and Verify the Output
Load the Spring application context using ClassPathXmlApplicationContext, fetch your bean, and call the display method:
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");
Employee emp = (Employee) context.getBean("employeeBean");
emp.displayEmployeeInfo();
}
}
Watch More Spring Tutorials
Click here to watch on Youtube:
https://www.youtube.com/watch?v=w7iXXCrD0pQ&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge:
| How to Inject String value using Spring dependency injection by constructor? | Spring Tutorial |
| How to Inject String value using Spring dependency injection by constructor? | Spring Tutorial |
| How to Inject String value using Spring dependency injection by constructor? | Spring Tutorial |
| How to Inject String value using Spring dependency injection by constructor? | Spring Tutorial |