Imagine I give you this.
@RestController
@GetMapping("/hello")
public String sayHello() {
return "Hello World";
}
You run it.
Open localhost:8080/hello
Browser says Hello World.
Cool.
But,
Who did all the work?
Because it definitely wasn't those five lines.
And also not magic πͺ
We wrote 5 Lines.
Spring Boot wrote the other 5000.
Let's investigate our first Spring Boot application.π΅οΈ
The goal is simple.
Browser -> Spring Boot -> Hello World
That's it.
Let's first dissect this mysterious-looking URL : localhost:8080/hello
- localhost :
It literally means your own computer.
Technically, localhost = 127.0.0.1
So localhost:8080 means talk to my computer, specifically the application listening on port 8080.
- But what's Port ?
Its like the the flat number of your apartment building. Food delivery doesn't stop at Sunshine Residency, it needs flat No.402.
Computers are equally dramatic.π
Your laptop may be running
-Chrome
-Spotify
-WhatsApp
-Zoom
-Spring Boot
all at the same time.
If a request reaches your machine, port number tells the computer which application should receive it.
Finally it's time we create a project.
You don't have to create a folder and start coding. You just need the Spring initializer.
Think of it as IKEA.
You don't build a cupboard from raw wood. (unless you run a DIY channel)
You buy a kit.
Everything is already arranged.
You only assemble it.
Spring Initializer does exactly that. It creates :
-Folder structure
-Maven setup
-Package structure
-Project metadata
-Dependencies
Before you touch the keyboard (to write code)
Now, incase you're wondering what's a dependency, I got you.
Imagine you're making chai. π΅
Do you grow tea leaves?
Raise cows? (although its better option for your mental health than reading this article)
Harvest sugar?
No.
Someone else already built those things.
You simply use them.
Similarly, a dependency is simply code someone else has already written so you don't have to. Its an external library your project needs, typically declared in pom.xml file.
Examples?
-Spring Web
-Spring Security
-Lombok
-MySQL Connector
Now lets look at the easiest piece of code.
@RestController :
It's like a receptionist everyone entering the office first talks to.
A controller receives incoming web requests and decides what response to send. @RestController is annotation that marks the class as capable of handling HTTP requests.
@GetMapping("/hello") :
This one tells Spring if someone knocks on '/hello' send them to the java method declared inside it.
The browser visits http://localhost:8080/hello, Spring maps the request to the annotated method, and the returned string becomes the response.
Hurray π
You just built your first Spring Boot application.
But here's the weird part.
You still don't know who actually started the server.
You never wrote socket programming.
Yet somehow everything worked.
Suspicious. (Not if you read the next article !)
Top comments (0)