Spring Hello World with Constructor Injection using XML

In this post, we will write a Hello World program in Spring using Maven.

We will use an xml based configuration file for managing dependencies.

We will be using constructor injection for injecting dependencies. The constructor injection will be for String literal.


First of all if you don’t have Maven, download maven and make sure to setup JAVA_HOME and PATH variables.

Please refer below article for this.

Maven Basics

Now, run the following command :

mvn archetype:generate -DartifactId=app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false


This will create a basic java project.

Now lets Import this project in eclipse :


The project is a normal java project.. We will need to add dependencies for Spring.

Lets add the Spring dependency under Dependencies section in  pom.xml.


Here is how the final pom.xml will look like :

<project xmlns=“” xmlns:xsi=“”


















We will be using XML based configuration in this post. So, lets add an xml file Spring.xml in src/main/java

In this xml, we are creating a Bean “firstBean”.

<beans xmlns=“”



<bean id=“firstBean” class=“”>

<constructor-arg value = “Techkatak”/>



Here is how the project structure should look like now :


Add a class under package:


public class Hello {

private String name;

public Hello(String name){ = name;


public void print(){

System.out.println(“Hello “ + name);



Also, add an under :



import org.springframework.context.ApplicationContext;


public class App


private static ApplicationContext context;

public static void main( String[] args )


context = new ClassPathXmlApplicationContext(“Spring.xml”);

Hello hello = (Hello) context.getBean(“firstBean”);




In this class, we are Spring provided ClassPathXmlApplicationContext class to create a Hello instance.


Here Spring is passing “Techkatak” as the constructor argument in Hello class’s constructor.


If you run this class , you will get the following output :


Hello Techkatak

© 2015, All rights reserved.