Java Notes
Complete introduction to Spring Boot - auto-configuration, starter dependencies, embedded servers, creating your first Spring Boot application, and project structure.
What is Spring Boot?
Spring Boot is a framework built on top of Spring Framework that eliminates boilerplate configuration and lets you build production-ready applications quickly. It follows the principle of "Convention over Configuration".
Creating a Spring Boot Project
Method 1: Spring Initializr (https://start.spring.io)
Select:
- Project: Maven
- Language: Java
- Spring Boot: 3.2.x
- Dependencies: Spring Web, Spring Data JPA, MySQL Driver, Lombok
Method 2: Maven pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.4</version>
</parent>
<groupId>com.example</groupId>
<artifactId>demo-app</artifactId>
<version>1.0.0</version>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>Project Structure
Main Application Class
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // = @Configuration + @EnableAutoConfiguration + @ComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}What @SpringBootApplication Does
| Component Annotation | Purpose |
|---|---|
@Configuration | Marks class as bean definition source |
@EnableAutoConfiguration | Enables auto-config based on classpath |
@ComponentScan | Scans current package and sub-packages |
application.properties
# Server Configuration
server.port=8080
server.servlet.context-path=/api
# Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA Configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
# Logging
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.file.name=app.log
# Custom Properties
app.name=Demo Application
app.version=1.0.0Building a Complete REST API
Model
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(unique = true, nullable = false)
private String email;
private int age;
@Column(name = "created_at")
private LocalDateTime createdAt = LocalDateTime.now();
}Repository
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
List<User> findByAgeGreaterThan(int age);
boolean existsByEmail(String email);
}Service
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
public User getUserById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new RuntimeException("User not found with id: " + id));
}
public User createUser(User user) {
if (userRepository.existsByEmail(user.getEmail())) {
throw new RuntimeException("Email already exists");
}
return userRepository.save(user);
}
public User updateUser(Long id, User userDetails) {
User user = getUserById(id);
user.setName(userDetails.getName());
user.setEmail(userDetails.getEmail());
user.setAge(userDetails.getAge());
return userRepository.save(user);
}
public void deleteUser(Long id) {
User user = getUserById(id);
userRepository.delete(user);
}
}Controller
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
return ResponseEntity.ok(userService.getAllUsers());
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
return ResponseEntity.ok(userService.getUserById(id));
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User created = userService.createUser(user);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
return ResponseEntity.ok(userService.updateUser(id, user));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return ResponseEntity.noContent().build();
}
}Running the Application
# Using Maven
mvn spring-boot:run
# Using JAR
mvn clean package
java -jar target/demo-app-1.0.0.jar
# With profile
java -jar app.jar --spring.profiles.active=prod
# With custom port
java -jar app.jar --server.port=9090Auto-Configuration Explained
When you add spring-boot-starter-web:
- Tomcat is auto-configured as embedded server
- DispatcherServlet is registered
- Jackson is configured for JSON serialization
- Error handling is set up
When you add spring-boot-starter-data-jpa:
- DataSource is auto-configured from properties
- EntityManagerFactory is created
- Transaction management is enabled
- Spring Data repositories are detected
Common Starter Dependencies
| Starter | Purpose |
|---|---|
spring-boot-starter-web | REST APIs and web apps |
spring-boot-starter-data-jpa | Database access with JPA |
spring-boot-starter-security | Authentication and authorization |
spring-boot-starter-validation | Input validation |
spring-boot-starter-test | Unit and integration testing |
spring-boot-starter-mail | Email sending |
spring-boot-starter-actuator | Production monitoring |
spring-boot-starter-cache | Caching support |
Interview Key Points
- Spring Boot = Spring Framework + Auto-configuration + Embedded Server
@SpringBootApplication=@Configuration+@EnableAutoConfiguration+@ComponentScan- Auto-configuration works based on classpath dependencies
- Embedded Tomcat eliminates need for external server
application.propertiesorapplication.ymlfor configuration- Spring Boot starters are curated dependency groups
- Fat JAR includes all dependencies for standalone deployment
- DevTools enables hot reload during development
Summary
In this chapter, we learned about Spring Boot Introduction in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Spring Boot Introduction.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, spring, framework, boot
Related Java Master Course Topics