Spring framework hello world

I don’t want to introduce with you all about what is Spring framework because there are a lot of tutorials about it. In this tutorial, I only focus on show with 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 the 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 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

To enable 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, to Spring can say “Hello world”, we need an object that can do that first.

Spring framework hello world

The content of class SayHello 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.

Spring framework hello worldThe content of the spring.xml file as below:

With the above declaration, Spring will create a new object for class SayHello, assign it to an id and store this object in 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”:


Spring framework hello world

Add Comment