Spring framework hello world

I don’t want to introduce you all to what is Spring framework because there are a lot of tutorials about it. In this tutorial, I only focus on showing you all how we can ask Spring to say “Hello world” 😀

Spring takes the Dependency Injection to implement its framework. That is the reason why I have a tutorial about Dependency Injection first. You should read this tutorial.

As you know, the idea of Dependency Injection that is: you don’t depend on anyone, when you need someone, you will call them. But the question here: someone who you will call, where are they from? Closely to Java programming, the object which you need, where are they from?

In the Spring framework, Spring will have a container to contain all objects which we need. When you need some objects, you just only call Spring to provide the objects.

OK, now I will show you a demo to ask Spring to say “Hello world”, to help you all can understand what I just said.

The first thing, we need a project to work on. Let’s create a Maven project as below:

Spring framework hello world

I will use Java 17 for this project:

To enable the Spring framework in our project, we need to add its dependency. Let open the pom.xml file in our project then add some lines as below:

Now, in order to Spring can say “Hello world”, we need an object that can do that first.

The content of the SayHello class is as below:

Then, we will add this object to the Spring container.

Spring manages the objects in 2 ways: by an XML file and by Annotations. In this tutorial, I just use an XML file. In the future, I will have some other tutorials using Annotation.

OK, now, let’s create an XML file in /src/main/resources folder of our project. The Spring configuration files should be here.

The content of the spring.xml file as below:

With the above declaration, Spring will create a new object for SayHello class, assign it to an id and store this object in the Spring container automatically.

As you see, Spring considers our object as beans, each bean has an id and we will use this id to call the object which we need.

Let’s see how Spring can say “Hello world”:


Add Comment