π Spring Boot: Server and Monitoring
The Story of the Smart Restaurant Kitchen
Imagine youβre running a restaurant. You need:
- A kitchen thatβs already set up and ready to cook (Embedded Server)
- Security locks on your ingredient storage (SSL/TLS)
- Magic tools that fix themselves while you cook (DevTools)
- Prep cooks who start working before customers arrive (Startup Runners)
- A health inspector who watches everything in real-time (Actuator)
Spring Boot gives you ALL of these, ready to go!
π³ Embedded Server Configuration
What Is It?
Think of an embedded server like a kitchen that comes built into your restaurant. You donβt need to build the kitchen separatelyβitβs already there when you open the doors!
Traditional Way: Build your app β Put it in a server (like Tomcat) β Hope it works Spring Boot Way: Your app comes WITH its own server inside! Just run it!
The Three Kitchen Types
graph TD A[Spring Boot App] --> B{Choose Your Kitchen} B --> C[π Tomcat<br/>Default Choice] B --> D[β‘ Jetty<br/>Lightweight] B --> E[π Undertow<br/>High Performance]
Simple Configuration
Change the port (which door customers enter):
# application.properties
server.port=8081
Change to Jetty instead of Tomcat:
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
Common Server Settings:
# How many customers can wait at the door
server.tomcat.max-connections=200
# How many chefs (threads) work at once
server.tomcat.threads.max=100
# Connection timeout (how long to wait)
server.connection-timeout=20000
π‘ Remember This!
Your app is a self-contained lunch box. Everything it needs is packed inside!
π SSL and TLS Configuration
What Is It?
SSL/TLS is like putting your secret recipe in an unbreakable safe. When someone orders food (sends data), they get a special key. Only they can open their delivery!
Without SSL: Anyone can read your messages With SSL: Messages are scrambled and only the right person can unscramble them
The Secret Handshake
graph TD A[π§ Customer Browser] -->|Hello! I want to talk securely| B[πͺ Your Server] B -->|Here's my certificate proving I'm real| A A -->|Great! Let's create a secret code| B B -->|Secret code accepted!| C[π Encrypted Chat Begins]
Setting Up SSL
Step 1: Create a keystore (your safe):
keytool -genkeypair -alias myapp \
-keyalg RSA -keysize 2048 \
-storetype PKCS12 \
-keystore keystore.p12 \
-validity 365
Step 2: Configure Spring Boot:
# Enable HTTPS
server.ssl.enabled=true
# Where is your safe?
server.ssl.key-store=classpath:keystore.p12
# Password to open the safe
server.ssl.key-store-password=mysecret
# Type of safe
server.ssl.key-store-type=PKCS12
# Name of the key inside
server.ssl.key-alias=myapp
Step 3: Force HTTPS everywhere:
@Configuration
public class HttpsConfig {
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat =
new TomcatServletWebServerFactory();
tomcat.addAdditionalTomcatConnectors(
httpToHttpsRedirectConnector());
return tomcat;
}
}
π‘ Key Point!
HTTPS = HTTP + S (Secure). The βSβ means your data travels in an armored truck, not an open bicycle!
π§ DevTools
What Is It?
DevTools is like having a magic assistant who instantly rebuilds your project whenever you make changes. No more stop-restart-wait-repeat!
The Magic Powers
graph TD A[βοΈ You Edit Code] --> B[π DevTools Detects Change] B --> C[β‘ Auto Restart in 1-2 seconds] C --> D[π See Changes Instantly!]
How to Get the Magic
Add DevTools:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
What DevTools Does:
| Feature | What It Means |
|---|---|
| Auto Restart | App restarts when code changes |
| LiveReload | Browser refreshes automatically |
| Caching Off | Always see fresh templates |
| Remote Debug | Debug apps running elsewhere |
Fine-tune the magic:
# Restart when these files change
spring.devtools.restart.additional-paths=src/main/java
# Don't restart for these
spring.devtools.restart.exclude=static/**
# Enable LiveReload (browser auto-refresh)
spring.devtools.livereload.enabled=true
π― Pro Tip!
DevTools only works in development. In production, itβs automatically disabled. Your deployed app stays fast and secure!
π Startup Runners
What Is It?
Startup Runners are like prep cooks who arrive early and get everything ready before the restaurant opens. Need to load some data? Warm up the cache? Check the database? Runners do it!
Two Types of Runners
graph TD A[App Starting...] --> B{Runner Type?} B --> C[CommandLineRunner<br/>Gets raw arguments] B --> D[ApplicationRunner<br/>Gets parsed arguments] C --> E[β App Ready!] D --> E
CommandLineRunner Example
@Component
public class DataLoader implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("Loading initial data...");
// Load users, products, settings
}
}
ApplicationRunner Example
@Component
public class StartupChecker implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
if (args.containsOption("init")) {
System.out.println("Running initialization...");
}
}
}
Control the Order
Have multiple runners? Control who goes first!
@Component
@Order(1) // This runs first
public class DatabaseInitRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("1. Setting up database...");
}
}
@Component
@Order(2) // This runs second
public class CacheWarmupRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("2. Warming up cache...");
}
}
π‘ When to Use?
Use runners for one-time startup tasks: loading data, checking connections, sending startup notifications, or warming caches!
π Actuator
What Is It?
Actuator is your appβs health inspector and dashboard. It tells you:
- Is the app healthy?
- How much memory is it using?
- What beans are loaded?
- Are databases connected?
The Inspection Toolkit
graph TD A[π Actuator] --> B[/health<br/>Is app alive?] A --> C[/info<br/>App details] A --> D[/metrics<br/>Numbers & stats] A --> E[/env<br/>Environment] A --> F[/beans<br/>All Spring beans]
Setting Up Actuator
Add the dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Configure what to expose:
# Show all endpoints
management.endpoints.web.exposure.include=*
# Or pick specific ones
management.endpoints.web.exposure.include=health,info,metrics
# Change the base path (default is /actuator)
management.endpoints.web.base-path=/manage
# Show full health details
management.endpoint.health.show-details=always
Key Endpoints
| Endpoint | What It Shows |
|---|---|
/actuator/health |
UP or DOWN status |
/actuator/info |
App version, description |
/actuator/metrics |
CPU, memory, requests |
/actuator/env |
All configuration properties |
/actuator/beans |
Every Spring bean |
/actuator/loggers |
Logging levels |
/actuator/httptrace |
Recent HTTP requests |
Custom Health Indicator
@Component
public class PaymentServiceHealth
implements HealthIndicator {
@Override
public Health health() {
if (isPaymentServiceUp()) {
return Health.up()
.withDetail("Payment", "Available")
.build();
}
return Health.down()
.withDetail("Payment", "Unavailable")
.build();
}
}
Security Warning! β οΈ
# In production, NEVER expose everything!
# Only expose what you need
management.endpoints.web.exposure.include=health,info
# Use a different port for management
management.server.port=9090
# Require authentication (via Spring Security)
π― Quick Summary
| Component | What It Does | Kitchen Analogy |
|---|---|---|
| Embedded Server | Runs your app | Built-in kitchen |
| SSL/TLS | Encrypts data | Security locks |
| DevTools | Fast development | Self-cleaning tools |
| Startup Runners | Pre-launch tasks | Prep cooks |
| Actuator | Monitoring | Health inspector |
π Your Next Steps
- β Run your first app with an embedded server
- β Add DevTools for faster development
- β Create a startup runner to load sample data
- β Explore Actuator endpoints
- β Secure with SSL when going to production
Youβve got this! Spring Boot makes the hard stuff easy. Your βrestaurantβ is ready to serve customers! π