Introduction to Spring & Environment Setup
8 min read
Introduction to Spring & Environment Setup
Welcome to the Spring framework. In the enterprise Java world, Spring is the absolute industry standard. If Java is the foundation of a building, Spring is the entire steel frame, plumbing, and electrical system pre-installed for you.
This guide will walk you through the core concepts of Spring, why it exists, how it works under the hood, and how to get your environment ready to build modern APIs. We will focus strictly on what you will use daily in the industry.
1. The "Why" Before the "How": Why the Spring Framework?
Definition
The Spring Framework is an open-source application framework that provides infrastructure support for developing Java applications. Spring Boot is an extension of this framework that provides pre-configured, production-ready setups (auto-configuration) to completely remove boilerplate setup.
The Problem
In the early 2000s, building enterprise Java applications (using vanilla Java EE) was notoriously heavy. Developers had to write massive XML configuration files, deploy to heavy application servers, and deal with hundreds of lines of boilerplate code just to get a simple web page running.
If you wanted to connect to a database, you had to manually open connections, manage connection pools, catch checked exceptions, and close the connections. It was highly error-prone. In fact, before Spring Boot, configuring a simple database connection often required more XML lines than the entire script of a short film.
The Concept
Spring was created to handle the infrastructure so you can focus strictly on the business logic. It promotes a lightweight, modular approach. You only bring in the parts of Spring you actually need (like Spring Web for APIs, or Spring Data for databases).
The Solution
Spring Boot solves the configuration nightmare via Auto-Configuration. It looks at the dependencies you have included in your project and automatically configures the necessary classes.
- Have
spring-boot-starter-webin your project? Spring Boot automatically embeds a Tomcat server and configures the web routing for you. - Have a database driver? It automatically sets up the connection pool.
You spend your time writing what the application does, not configuring how it starts.
2. Demystifying the Core: Inversion of Control (IoC) and Dependency Injection (DI)
Definition
Inversion of Control (IoC) is a software design principle where the control flow of a program is inverted: instead of the programmer's custom code controlling the flow and creating objects, an external framework takes control of object creation and lifecycle management.
Dependency Injection (DI) is a specific implementation of IoC. It is a design pattern where an object receives its dependencies from an external source rather than instantiating them internally.
The Problem
Imagine you have a PaymentController class that processes transactions, and it needs a StripePaymentService to talk to the Stripe API.
Normally, you might write:
public class PaymentController {
private StripePaymentService paymentService = new StripePaymentService();
}This causes tight coupling.
PaymentControlleris now permanently chained toStripePaymentService.- If
StripePaymentServicerequires a database connection in its constructor tomorrow, you have to modifyPaymentControllerto pass it. - If you want to write a unit test for
PaymentController, you cannot easily replace the real Stripe service with a fake one (a mock), meaning your tests might accidentally charge real credit cards!
The Concept
Spring solves this by utilizing an IoC Container. In Spring, the objects managed by this container are called Beans.
Instead of classes creating their own dependencies, the Spring IoC Container creates all the Beans at startup, holds them in memory, and injects them wherever they are requested.
The Solution
With Dependency Injection, your code changes to this:
@RestController
public class PaymentController {
private final PaymentService paymentService;
// Spring sees this constructor and injects the service automatically!
public PaymentController(PaymentService paymentService) {
this.paymentService = paymentService;
}
}Imagine you are running a busy pizza shop. You are the chef (PaymentController). If you have to personally leave the kitchen to milk a cow and make cheese (new StripePaymentService()) every time a new customer orders a pizza, you are going to fail. Instead, you need a system where the shop manager (the IoC Container) prepares the cheese in advance and hands it to you (via Dependency Injection) exactly when you need it at your station. You just ask for "Cheese", and you don't care how the manager made it.
3. Setting up the Environment: JDK, IDEs, and Build Tools (Maven/Gradle)
Before writing any Spring code, we need to assemble our workstation. As of 2026, the industry standards have moved forward. Java 17 is the absolute baseline, but Java 21 is the recommended Long-Term Support (LTS) version used in modern enterprise environments [1, 5].
The Problem
Java requires a compiler and runtime environment. Furthermore, downloading external libraries (like Spring, database drivers, or testing tools) manually by dragging and dropping .jar files into a folder is unscalable and creates "it works on my machine" bugs.
The Concept & Solution
We need three things: a JDK, an IDE, and a Build Tool.
JDK (Java Development Kit):
You need JDK 21 [5]. You can download it via Eclipse Adoptium (Temurin).
To verify your installation, open your terminal and run:bashjava -versionOutput should show version 21.x.x.
IDE (Integrated Development Environment):
IntelliJ IDEA (Community or Ultimate) is the undisputed industry standard for Java and Spring development. It provides built-in Spring support, intelligent code completion, and seamless Maven integration.Build Tools (Maven vs. Gradle):
A build tool automates the process of downloading dependencies and compiling your code.- Maven uses an XML file (
pom.xml). It is strict, universally understood, and the standard for 80% of enterprise Spring apps. - Gradle uses a Groovy/Kotlin script (
build.gradle). It is faster for massive monoliths but has a steeper learning curve. - Industry Practice: We will use Maven. It is highly reliable and everywhere in the Spring ecosystem.
- Maven uses an XML file (
4. Your First Spring Boot App: The Magic of Spring Initializr and "Hello World"
Definition
Spring Initializr is a web-based utility provided by the Spring team to quickly generate a boilerplate Spring Boot project with the correct folder structure and compatible dependency versions.
The Problem
Setting up a Maven project from scratch means creating src/main/java and src/test/java folders, writing a pom.xml manually, and hoping you picked dependency versions that do not conflict with each other. It is tedious.
The Concept
Spring Initializr completely automates the boilerplate generation. You pick what you need, and it hands you a zip file ready to be opened in your IDE.
The Solution: Getting Started
Step 1: Generate the Boilerplate
- Go to start.spring.io
- Fill out the configuration exactly like this for a modern 2026 setup [1]:
- Project: Maven
- Language: Java
- Spring Boot: 3.4.x or 4.0.x (Whatever is marked as the latest stable) [2, 8]
- Group:
com.freecodecamp - Artifact:
hello-spring - Packaging: Jar
- Java: 21 [5]
- Click Add Dependencies and search for:
- Spring Web: This allows us to build RESTful APIs and embeds an Apache Tomcat server.
- Click Generate. Download the
.zipfile, extract it, and open the folder in IntelliJ IDEA.
Step 2: Understanding the Boilerplate Code
Navigate to src/main/java/com/freecodecamp/hellospring/HelloSpringApplication.java. You will see this:
package com.freecodecamp.hellospring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloSpringApplication {
public static void main(String[] args) {
SpringApplication.run(HelloSpringApplication.class, args);
}
}Under the hood: The @SpringBootApplication annotation is actually a combination of three different annotations:
@Configuration: Marks this class as a source of bean definitions.@EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings (e.g., setting up a Tomcat server because it sawspring-boot-starter-webin yourpom.xml).@ComponentScan: Tells Spring to look for other components, configurations, and services in thecom.freecodecamp.hellospringpackage, allowing it to find your custom code.
Step 3: Creating a Hello World Endpoint
Let's create an API endpoint so the browser can talk to our application.
Create a new file in the same folder named HelloController.java.
package com.freecodecamp.hellospring;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, freeCodeCamp! Spring Boot is running.";
}
}@RestController: Tells the IoC container to create a Bean of this class, and indicates that every method returns data directly to the user (instead of rendering an HTML page).@GetMapping("/hello"): Maps HTTP GET requests sent to/helloto this specific method.
Step 4: Run the App!
Click the green "Play" button in IntelliJ next to your main method in HelloSpringApplication.java.
In the console, you will see a Spring logo (the "banner") and a line saying:Tomcat started on port(s): 8080 (http)
Open your web browser and go to: http://localhost:8080/hello
You will see your text! You have successfully configured Java, used a build tool, leveraged Inversion of Control, and utilized Auto-Configuration to stand up a web server in minutes.
References for Extra Reading
Challenge
You are tasked with building a simple RESTful API using Spring Boot that demonstrates the core principles of Dependency Injection (DI) and Inversion of Control (IoC). Your API will have a service layer and a controller layer.
Requirements:
Create a Service Bean:
- Define a Java class named
MessageService. - This class must be managed by the Spring IoC container as a service component.
- It should contain one public method,
generateWelcomeMessage(), which takes no arguments and returns theString:"Welcome to Enterprise Spring!".
- Define a Java class named
Create a REST Controller:
- Define a Java class named
WelcomeController. - This class must be configured to handle incoming web requests as a REST controller.
- Use constructor injection to inject an instance of
MessageService. You must not create theMessageServiceinstance yourself using thenewkeyword.
- Define a Java class named
Create a GET Endpoint:
- Inside
WelcomeController, create a public methodgetWelcome(). - This method should use the injected
MessageServiceinstance to callgenerateWelcomeMessage()and return the result. - Map this method to respond to HTTP GET requests at the
/welcomepath.
- Inside
Create the Main Application Class:
- Define a class named
MainApplication. - Annotate this class to enable Spring Boot's auto-configuration, component scanning, and to mark it as a configuration class.
- Include the standard
mainmethod required to launch the Spring Boot application.
- Define a class named
Expected result
Your final code should consist of three complete Java classes with all necessary imports. The solution must correctly implement Dependency Injection without manually instantiating the service within the controller.
MessageService.java
- Must be annotated with
@Servicefromorg.springframework.stereotype.Service. - Must contain a
public String generateWelcomeMessage()method.
WelcomeController.java
- Must be annotated with
@RestControllerfromorg.springframework.web.bind.annotation.RestController. - Must have a
private finalfield forMessageService. - Must have a single
publicconstructor that acceptsMessageServiceas an argument to perform constructor injection. - Must contain a
getWelcome()method annotated with@GetMapping("/welcome")fromorg.springframework.web.bind.annotation.GetMapping. - The
getWelcome()method must return the value from calling the service'sgenerateWelcomeMessage()method.
MainApplication.java
- Must be annotated with
@SpringBootApplicationfromorg.springframework.boot.autoconfigure.SpringBootApplication. - Must contain a
public static void main(String[] args)method. - The
mainmethod's body should be a single call toSpringApplication.run(MainApplication.class, args);, withorg.springframework.boot.SpringApplicationimported.