Spring Boot
Spring Boot is a framework that simplifies Java application development by providing production-ready defaults and minimal configuration. This cheatsheet covers essential commands for initialization, development, and deployment.
Basic Commands
| Command | Description |
|---|---|
spring --version | Show Spring CLI version |
spring --help | Display help information |
mvn spring-boot:run | Run Spring Boot app with Maven |
gradle bootRun | Run Spring Boot app with Gradle |
java -jar app.jar | Run packaged JAR file |
java -jar app.jar --server.port=9000 | Run on custom port |
mvn spring-boot:build-image | Create Docker image with Maven |
gradle bootBuildImage | Create Docker image with Gradle |
Installation & Setup
Install Spring CLI
# macOS with Homebrew
brew tap spring-io/tap
brew install spring-boot
# Linux/Ubuntu - Download SDK
curl https://sdkman.io | bash
sdk install springboot
sdk use springboot latest
# Windows with Chocolatey
choco install springboot
Create New Project
# Using Spring CLI (interactive)
spring project create --from https://start.spring.io my-app
# Using Maven
mvn archetype:generate \
-DgroupId=com.example \
-DartifactId=my-app \
-DarchetypeArtifactId=maven-archetype-quickstart
# Using Gradle
spring project create --build gradle --language java my-app
# Via Spring Initializr CLI
spring project create --dependencies web,jpa,mysql my-app
Build & Compile
| Command | Description |
|---|---|
mvn clean install | Build with Maven (clean, compile, test, package) |
mvn clean compile | Compile only without creating JAR |
mvn clean test | Run unit tests |
mvn clean verify | Build and verify application |
gradle build | Build with Gradle |
gradle clean | Clean build artifacts |
gradle test | Run Gradle tests |
gradle assemble | Create JAR/WAR without testing |
Application Configuration
application.properties
# Server configuration
server.port=8080
server.servlet.context-path=/api
server.shutdown=graceful
# Application name and version
spring.application.name=my-app
app.version=1.0.0
# Logging
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.pattern.console=%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
# 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
spring.jpa.hibernate.ddl-auto=update
# JPA/Hibernate
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
Development Configuration
# Run with specific profile
java -jar app.jar --spring.profiles.active=dev
mvn spring-boot:run -Dspring-boot.run.arguments="--spring.profiles.active=dev"
# Override properties at runtime
java -jar app.jar --server.port=9000 --logging.level.root=DEBUG
# Load from external config file
java -jar app.jar --spring.config.location=classpath:,file:./config/
# Set Java system properties
java -Dspring.profiles.active=prod -jar app.jar
Actuator & Monitoring
# Enable actuator endpoints
spring.boot.actuator.endpoints.web.exposure.include=*
spring.boot.actuator.endpoints.web.base-path=/actuator
# Common actuator endpoints
curl http://localhost:8080/actuator
curl http://localhost:8080/actuator/health
curl http://localhost:8080/actuator/metrics
curl http://localhost:8080/actuator/env
curl http://localhost:8080/actuator/beans
Spring Security Configuration
Basic Security Setup
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
JWT Authentication
# Add Spring Security & JWT dependencies to pom.xml
# <dependency>
# <groupId>org.springframework.boot</groupId>
# <artifactId>spring-boot-starter-security</artifactId>
# </dependency>
# <dependency>
# <groupId>io.jsonwebtoken</groupId>
# <artifactId>jjwt</artifactId>
# <version>0.11.5</version>
# </dependency>
Logging Configuration
SLF4J with Logback
<!-- logback-spring.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<springProperty name="LOG_FILE" source="logging.file.name" defaultValue="logs/app.log"/>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>logs/app-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>10MB</maxFileSize>
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>
<root level="INFO">
<appender-ref ref="FILE"/>
</root>
</configuration>
Runtime Log Level Control
# Change log level via Actuator (Spring Boot 2.0+)
curl -X POST http://localhost:8080/actuator/loggers/com.example \
-H "Content-Type: application/json" \
-d '{"configuredLevel":"DEBUG"}'
# View current log levels
curl http://localhost:8080/actuator/loggers
Testing Spring Boot Applications
Maven Testing
# Run all tests
mvn test
# Run specific test class
mvn test -Dtest=UserControllerTest
# Run specific test method
mvn test -Dtest=UserControllerTest#testGetUser
# Skip tests during build
mvn clean install -DskipTests
# Run tests with debug output
mvn test -X
Gradle Testing
# Run all tests
gradle test
# Run specific test class
gradle test --tests UserControllerTest
# Run with verbose output
gradle test --info
Test Configuration
@SpringBootTest
public class ApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {
}
@Test
public void testEndpoint() {
ResponseEntity<String> response = restTemplate.getForEntity(
"/api/users", String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
}
}
Common Issues & Solutions
Port already in use
# Find process using port 8080
lsof -i :8080
netstat -tulpn | grep 8080
# Kill process or use different port
kill -9 <PID>
java -jar app.jar --server.port=9000
Build fails with memory error
# Increase Maven heap size
export MAVEN_OPTS="-Xmx1024m"
mvn clean install
# Or set in terminal
GRADLE_OPTS="-Xmx1024m" gradle build
Database connection issues
# Check datasource configuration
curl http://localhost:8080/actuator/env | grep datasource
# Test MySQL connection
mysql -h localhost -u root -p -e "SELECT VERSION();"
Deployment
Docker Deployment
# Build Docker image (Maven)
mvn spring-boot:build-image -Dspring-boot.build-image.name=myapp:1.0
# Build Docker image (Gradle)
gradle bootBuildImage
# Run containerized app
docker run -p 8080:8080 myapp:1.0
# Run with environment variables
docker run -p 8080:8080 \
-e SPRING_DATASOURCE_URL=jdbc:mysql://db:3306/mydb \
-e SPRING_DATASOURCE_USERNAME=root \
myapp:1.0
Production JAR Execution
# Run with JVM tuning
java -Xmx512m -Xms256m -XX:+UseG1GC \
-Dspring.profiles.active=prod \
-jar app.jar
# Run in background with nohup
nohup java -jar app.jar > app.log 2>&1 &
# Create systemd service
[Unit]
Description=My Spring Boot App
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/java -jar /opt/app.jar
Restart=on-failure
RestartSec=10
Performance Tuning
# Enable HTTP/2
server.http2.enabled=true
# Connection pooling
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
# Caching configuration
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
REST API Development
REST Controller Example
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
return ResponseEntity.ok(userService.findAll());
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
return userService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
return ResponseEntity
.status(HttpStatus.CREATED)
.body(userService.save(user));
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(
@PathVariable Long id,
@RequestBody User user) {
return ResponseEntity.ok(userService.update(id, user));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteById(id);
return ResponseEntity.noContent().build();
}
}
Testing APIs with curl
# GET request
curl http://localhost:8080/api/users
# POST request
curl -X POST http://localhost:8080/api/users \
-H "Content-Type: application/json" \
-d '{"name":"John","email":"john@example.com"}'
# PUT request
curl -X PUT http://localhost:8080/api/users/1 \
-H "Content-Type: application/json" \
-d '{"name":"Jane","email":"jane@example.com"}'
# DELETE request
curl -X DELETE http://localhost:8080/api/users/1
Environment Variables
| Variable | Description |
|---|---|
SPRING_PROFILES_ACTIVE | Active Spring profiles |
JAVA_OPTS | JVM options |
MAVEN_OPTS | Maven JVM options |
SERVER_PORT | Server port |
SERVER_SERVLET_CONTEXT_PATH | Context path |
SPRING_DATASOURCE_URL | Database URL |
SPRING_DATASOURCE_USERNAME | DB username |
SPRING_DATASOURCE_PASSWORD | DB password |
Maven pom.xml Example
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-app</artifactId>
<version>1.0.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<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-java</artifactId>
<version>8.0.33</version>
</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>
Examples
Basic Workflow
# 1. Initialize spring-boot
spring-boot init
# 2. Configure basic settings
spring-boot config set port 8080
# 3. Start service
spring-boot start
# 4. Check status
spring-boot status
# 5. Perform operations
spring-boot run --target example.com
# 6. View results
spring-boot results
# 7. Stop service
spring-boot stop
Advanced Workflow
# Comprehensive operation with monitoring
spring-boot run \
--config production.yaml \
--parallel \
--workers 8 \
--verbose \
--timeout 300 \
--output json \
--log-file operation.log
# Monitor in real-time
spring-boot monitor --real-time --interval 5
# Generate report
spring-boot report --type comprehensive --output report.html
Automation Example
#!/bin/bash
# Automated spring-boot workflow
# Configuration
TARGETS_FILE="targets.txt"
RESULTS_DIR="results/$(date +%Y-%m-%d)"
CONFIG_FILE="automation.yaml"
# Create results directory
mkdir -p "$RESULTS_DIR"
# Process each target
while IFS= read -r target; do
echo "Processing $target..."
spring-boot \
--config "$CONFIG_FILE" \
--output json \
--output-file "$RESULTS_DIR/$\\\\{target\\\\}.json" \
run "$target"
done < "$TARGETS_FILE"
# Generate summary report
spring-boot report summary \
--input "$RESULTS_DIR/*.json" \
--output "$RESULTS_DIR/summary.html"
Best Practices
Security
- Always verify checksums when downloading binaries
- Use strong authentication methods (API keys, certificates)
- Regularly update to the latest version
- Follow principle of least privilege
- Enable audit logging for compliance
- Use encrypted connections when possible
- Validate all inputs and configurations
- Implement proper access controls
Performance
- Use appropriate resource limits for your environment
- Monitor system performance regularly
- Optimize configuration for your use case
- Use parallel processing when beneficial
- Implement proper caching strategies
- Regular maintenance and cleanup
- Profile performance bottlenecks
- Use efficient algorithms and data structures
Operational
- Maintain comprehensive documentation
- Implement proper backup strategies
- Use version control for configurations
- Monitor and alert on critical metrics
- Implement proper error handling
- Use automation for repetitive tasks
- Regular security audits and updates
- Plan for disaster recovery
Development
- Follow coding standards and conventions
- Write comprehensive tests
- Use continuous integration/deployment
- Implement proper logging and monitoring
- Document APIs and interfaces
- Use version control effectively
- Review code regularly
- Maintain backward compatibility
Resources
Official Documentation
Community Resources
Learning Resources
- Getting Started Guide
- Tutorial Series
- Best Practices Guide
- Video Tutorials
- Training Courses
- Certification Program
Related Tools
- Git - Complementary functionality
- Docker - Alternative solution
- Kubernetes - Integration partner
Last updated: 2025-07-06|Edit on GitHub