← Back | Spring Boot Basics
Week 1–2
Week 1–2 · Core Backend

Spring Boot Basics

Spring Boot makes Java web development fast by auto-configuring everything. You focus on writing business logic — Spring handles the boring setup. Let's build your first REST API.

🌱 Spring Boot 3.x REST API Dependency Injection
🧠
Concept
Spring Framework vs Spring Boot
Spring Framework is like IKEA furniture — very powerful and flexible, but you have to assemble everything yourself (lots of XML config).

Spring Boot is like buying furniture fully assembled and ready to use — it comes with smart defaults (auto-configuration) so you can start immediately. And if you don't like a default, you can override it.
Spring FrameworkSpring Boot
Manual XML/Java configurationAuto-configuration with sensible defaults
Need external Tomcat serverEmbedded Tomcat — run with java -jar
Complex dependency managementStarter POMs bundle compatible versions
Verbose setupProduction-ready in minutes
Spring Boot 3.x requires Java 17+. We use Java 21 in this course which is fully compatible. Spring Boot 3 also supports native compilation via GraalVM.
🚀
Approach 1 — Quick Start
Create a Spring Boot Project
Using VS Code Spring Initializr extension — fastest way inside your editor
1

Install the Extension

In VS Code, open Extensions (Ctrl+Shift+X) and install Spring Boot Extension Pack by VMware. This includes the Spring Initializr Java Support extension.

2

Open the Command Palette

Press Ctrl+Shift+P → type Spring Initializr: Create a Maven Project → press Enter.

3

Answer the prompts

VS Code will ask you each field one at a time in the top bar:

  • Spring Boot version → 3.x.x
  • Group ID → com.campustoai
  • Artifact ID → student-api
  • Packaging → Jar
  • Java version → 21
4

Select Dependencies

A multi-select list appears. Search and select:

  • Spring Web
  • Spring Boot DevTools
  • Lombok

Press Enter when done.

5

Choose folder & open

VS Code asks where to save the project. Pick a folder → click Generate into this folder. The project opens automatically — no zip, no extract.

Why use this? Faster than the browser — you never leave VS Code. No download/extract step. Ideal for creating multiple microservice projects quickly.
🌐
Approach 2
Create a Project via start.spring.io (Web)
Step-by-step walkthrough of every field in the form
start.spring.io is the official Spring project generator maintained by the Spring team. It produces a ready-to-run Maven or Gradle project in seconds — no IDE plugin needed.
1

Open the generator

Go to start.spring.io in any browser. You will see a form with several fields — here is what each one means.

2

Project — Build tool

Choose the tool that compiles and packages your code.

OptionWhat it isWhen to use
MavenUses pom.xml. Very common in Indian tech companies.Use this for this course
GradleUses build.gradle. Faster builds, popular in Android.Skip for now
3

Group ID — Your organisation's namespace

Group ID uniquely identifies your organisation or project family across all Maven projects in the world. It is written in reverse domain-name format.

Analogy: Think of Group ID like a postal PIN code for your company. Just like PIN 400001 means a specific area in Mumbai, com.zomato means "a project by Zomato". It prevents name collisions — two different companies can both have a project called user-service, but their Group IDs are different.
Company / DomainGroup ID
campustoai.comcom.campustoai
zomato.comcom.zomato
flipkart.inin.flipkart
Your startupcom.yourstartup

Group ID also becomes the root Java package for your code. So com.campustoai means your Java files will live under com/campustoai/.

Use lowercase letters only. No spaces. Use dots to separate parts. Common pattern: com.company or com.company.team.
4

Artifact — Your project's name

Artifact is the name of this specific project or microservice. It becomes the name of the final JAR file that gets built.

Analogy: If Group ID is your company name (e.g., "Amazon"), then Artifact is the specific product name (e.g., "prime-video" or "delivery-service"). Together they give a fully unique identity: com.amazon:delivery-service.
Artifact valueJAR file produced
student-apistudent-api-0.0.1-SNAPSHOT.jar
payment-servicepayment-service-0.0.1-SNAPSHOT.jar
auth-serviceauth-service-0.0.1-SNAPSHOT.jar
Use lowercase letters and hyphens only. No spaces, no underscores. Keep it short and descriptive — it describes what this service does.
5

Name & Description

Name is auto-filled from Artifact. It becomes the main class name (e.g., artifact student-api → class StudentApiApplication). You can leave it as-is.

Description is a plain English sentence about your project. It only appears in pom.xml as a comment — no functional impact.

6

Packaging — How your app is bundled

Packaging decides the format of the file Maven builds when you run mvn package.

OptionFile producedHow to runWhen to use
Jar ✅ .jar (Java Archive) java -jar app.jar
Tomcat is embedded inside the jar
Modern Spring Boot apps, microservices, Docker containers, cloud deployments. Always use this.
War .war (Web Archive) Deploy to an external Tomcat or JBoss server Legacy enterprise apps that already have a corporate Tomcat server. Avoid unless required.
Analogy: JAR is like a food truck — the kitchen and the food are all in one vehicle, you just drive it anywhere and serve. WAR is like a restaurant that needs to be installed inside an existing building (Tomcat server) before it can serve food.
Always choose Jar for this course and for any new Spring Boot project. It is cloud-ready, Docker-friendly, and the Spring Boot default.
7

Java Version

Select 21 (LTS — Long Term Support). Spring Boot 3.x requires Java 17 minimum. Java 21 is the latest LTS release and what this course uses.

8

Dependencies — What your project needs

Click ADD DEPENDENCIES and search for:

🌐 Spring Web
This is the core dependency for any REST API. Without it, your Spring Boot app has no web server and cannot handle HTTP requests.

It bundles three things for you automatically:
Spring MVC — the framework that maps HTTP requests to your @GetMapping / @PostMapping methods
Embedded Tomcat — the web server. No separate Tomcat installation needed; it starts inside your JAR
Jackson — the JSON library. Converts your Java objects ↔ JSON automatically. When you return a Student object from a controller, Jackson turns it into {"id":1,"name":"Rahul"}
⚡ Spring Boot DevTools
A development-only helper that monitors your project files. Every time you save a .java file, it automatically restarts the Spring context (in ~1 second instead of restarting the whole JVM which takes 4–5 seconds).

Without DevTools: Change code → stop server manually → run again → wait 5 sec
With DevTools: Change code → save → app reloads in 1 sec automatically

Note: DevTools is automatically excluded from production builds — it only activates during development.
🔧 Lombok
Java classes require a lot of repetitive code — getters, setters, constructors, equals, hashCode, toString. Lombok generates all of this at compile time using annotations, so you don't write it.

Without Lombok (you write ~30 lines): private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } // ... same for every field With Lombok (you write 3 lines): @Data // generates ALL getters, setters, equals, hashCode, toString @AllArgsConstructor // generates constructor with all fields @NoArgsConstructor // generates empty constructor (needed for JSON) public class Student { private String name; private String email; }
9

Generate & Open

Click the GENERATE button (or press Ctrl+Enter). A .zip file downloads. Extract it to a folder, then open that folder in VS Code with File → Open Folder.

VS Code's Java Extension Pack will auto-detect the Maven project and download all dependencies in the background. Watch the bottom status bar — it shows "Java: Importing project…".
Quick reference — form values for this course:

Project: Maven  |  Language: Java  |  Spring Boot: 3.x.x
Group: com.campustoai  |  Artifact: student-api
Packaging: Jar  |  Java: 21
📁
Step 2
Understanding the Project Structure
student-api/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/campustoai/studentapi/ │ │ │ └── StudentApiApplication.java ← Entry point │ │ └── resources/ │ │ └── application.properties ← Config file │ └── test/ │ └── java/ │ └── com/campustoai/studentapi/ │ └── StudentApiApplicationTests.java └── pom.xml ← Dependencies
File / FolderPurpose
StudentApiApplication.javaMain class with main() method. Starts the Spring app and embedded Tomcat.
application.propertiesConfiguration: server port, database URL, log level, etc.
pom.xmlDependencies (Spring Web, JPA, etc.) and build config.
src/test/Unit and integration tests.
StudentApiApplication.java
@SpringBootApplication // This single annotation does 3 things: // 1. @Configuration — marks this as config class // 2. @EnableAutoConfiguration — auto-configures Spring beans // 3. @ComponentScan — scans this package for @Component, @Service, @Controller public class StudentApiApplication { public static void main(String[] args) { SpringApplication.run(StudentApiApplication.class, args); } }
🔧
Core Concept
Dependency Injection (DI)
The most important Spring concept to understand
Analogy: Imagine a restaurant. The chef (Controller) needs a knife (Service). Instead of the chef buying their own knife (creating object with new), the restaurant manager (Spring IoC Container) provides the knife. The chef just declares "I need a knife" and it appears.

This is Inversion of Control (IoC) — you give control of object creation to the Spring container, not your code.

Without DI (bad — tight coupling)

public class StudentController { // Bad: controller creates its own dependency private StudentService service = new StudentService(); // Problem: hard to test, can't swap implementations }

With DI (good — loose coupling)

@RestController public class StudentController { // Spring injects the service — controller doesn't create it private final StudentService studentService; // Constructor injection — RECOMMENDED (immutable, testable) public StudentController(StudentService studentService) { this.studentService = studentService; } } @Service // Tells Spring: create and manage this as a bean public class StudentService { public List<String> getAllStudents() { return List.of("Rahul", "Priya", "Amit"); } }
Spring stereotypes: @Component (generic), @Service (business logic), @Repository (data access), @Controller/@RestController (web layer). All are detected by @ComponentScan.
🌐
Step 3
Build Your First REST Controller
A working CRUD API for students
Student.java (Model)
public class Student { private Long id; private String name; private String email; // Constructors, getters, setters // (or use @Data from Lombok to auto-generate these) }
StudentController.java
@RestController // Combines @Controller + @ResponseBody @RequestMapping("/api/students") // Base path for all endpoints public class StudentController { private final List<Student> students = new ArrayList<>(); private long nextId = 1; // GET /api/students → returns all students @GetMapping public List<Student> getAll() { return students; } // GET /api/students/1 → returns student with id=1 @GetMapping("/{id}") public Student getById(@PathVariable Long id) { return students.stream() .filter(s -> s.getId().equals(id)) .findFirst() .orElseThrow(() -> new RuntimeException("Not found")); } // POST /api/students → creates a new student @PostMapping @ResponseStatus(HttpStatus.CREATED) public Student create(@RequestBody Student student) { student.setId(nextId++); students.add(student); return student; } // DELETE /api/students/1 → removes student with id=1 @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable Long id) { students.removeIf(s -> s.getId().equals(id)); } }
Test with Postman: Run the app (mvn spring-boot:run), then send a GET request to http://localhost:8080/api/students. You'll get an empty list []. Try a POST with JSON body {"name":"Rahul","email":"rahul@email.com"}.
⚙️
Step 4
application.properties
Configure your application without changing code
src/main/resources/application.properties
# Change the default port (default is 8080) server.port=8081 # Application name (shown in logs) spring.application.name=student-api # Log level for your package logging.level.com.campustoai=DEBUG # Database config (add when you add Spring Data JPA) # spring.datasource.url=jdbc:postgresql://localhost:5432/studentdb # spring.datasource.username=postgres # spring.datasource.password=secret # JPA settings # spring.jpa.show-sql=true # spring.jpa.hibernate.ddl-auto=create-drop
application.yml alternative: You can also use application.yml (YAML format) instead of .properties. Both work. Many teams prefer YAML for its readability and ability to nest config naturally.
Step 5
Run the Application
Spring Boot DevTools for faster development

Run from terminal

mvn spring-boot:run

Spring Boot starts an embedded Tomcat server. Look for this line in the logs:

Tomcat started on port(s): 8080 (http) Started StudentApiApplication in 2.1 seconds

DevTools — Auto-restart on save

With spring-boot-devtools in pom.xml, every time you save a file, Spring Boot automatically restarts (in ~1 second instead of 3-4 seconds). Enable it in VS Code's Java settings.

Common Annotations Reference

AnnotationPurpose
@SpringBootApplicationMain class — enables auto-config + component scan
@RestControllerClass handles HTTP requests, returns JSON
@RequestMappingMaps URL path to a class or method
@GetMappingHTTP GET request handler
@PostMappingHTTP POST request handler
@PutMappingHTTP PUT request handler
@DeleteMappingHTTP DELETE request handler
@PathVariableExtract value from URL path: /students/{id}
@RequestBodyMap JSON request body to Java object
@RequestParamExtract query param: /students?page=2
@ServiceBusiness logic layer bean
@AutowiredInject a dependency (prefer constructor injection)
🎯
Interview Prep
Common Interview Questions
QWhat is Spring Boot? How is it different from the Spring Framework?

Spring Boot is an opinionated framework built on top of Spring Framework that simplifies application setup. Spring Framework is flexible but requires extensive XML/Java configuration. Spring Boot provides:

  • Auto-configuration — detects libraries on classpath and configures them automatically
  • Embedded server — Tomcat/Jetty included, no separate installation needed
  • Starter POMs — curated dependency bundles (spring-boot-starter-web includes Spring MVC + Jackson + Tomcat)
  • Actuator — production-ready monitoring endpoints out of the box
QWhat does @SpringBootApplication do?

It's a convenience annotation that combines three annotations:

  • @Configuration — marks the class as a source of Spring bean definitions
  • @EnableAutoConfiguration — tells Spring Boot to auto-configure beans based on the classpath
  • @ComponentScan — scans the package (and sub-packages) for @Component, @Service, @Controller, @Repository beans
QWhat is Dependency Injection and what are the types?

Dependency Injection is a design pattern where an object receives its dependencies from outside rather than creating them. Spring manages object creation and wiring.

Three types:

  • Constructor injection (recommended) — dependencies passed via constructor, supports final fields, makes testing easy
  • Setter injection — dependencies set via setter methods, allows optional dependencies
  • Field injection (@Autowired on field) — convenient but makes testing harder, not recommended for production
QWhat is the difference between @Controller and @RestController?

@Controller is used for traditional MVC web applications where methods return view names (HTML templates like Thymeleaf). The return value is resolved to a view by ViewResolver.

@RestController = @Controller + @ResponseBody. Every method's return value is automatically serialised to JSON (or XML) and written directly to the HTTP response. Used for building REST APIs.

QWhat is @RequestBody and @PathVariable?

@RequestBody maps the HTTP request body (JSON/XML) to a Java object. Used with POST/PUT. Jackson library converts JSON → Java object automatically.

@PathVariable extracts a value from the URL path. For @GetMapping("/students/{id}"), the {id} in the URL is extracted with @PathVariable Long id.

@RequestParam extracts query parameters from the URL: /students?page=2&size=10.

QWhat is IoC (Inversion of Control)?

IoC is a principle where the control of object creation and dependency wiring is given to a framework/container instead of the application code. In traditional programming, your code calls a library. With IoC, the framework calls your code.

Spring's IoC Container (ApplicationContext) creates beans, manages their lifecycle, and injects dependencies. You just annotate your classes and Spring does the rest.