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 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 say “Hello world”, to help you all can understand what I just said.

The first thing, we need a project to work. Let 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 can do that first.

Spring framework hello world

The content of class SayHello as below:

Then, we will add this object to Spring container.

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

OK, now, let 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 spring.xml file as below:

With 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 to the object which we need.

Let see how Spring can say “Hello world”:


Spring framework hello world

Chia sẽ bài viết này ...Share on Facebook
0Tweet about this on Twitter
Share on LinkedIn

Add Comment