Spring Boot: Java Backend Development
Enterprise-grade Java applications with Spring Boot framework and microservices. Complete guide to building robust Java backend applications with Spring Boot.
What You'll Master
Spring Boot Fundamentals
Auto-configuration, starters, and application properties
RESTful Web Services
Building REST APIs with Spring Web MVC
Data Access & JPA
Spring Data JPA, repositories, and database integration
Security & Authentication
Spring Security, JWT, and OAuth2 integration
Microservices Architecture
Service discovery, configuration, and communication
Testing & Deployment
Unit testing, integration testing, and production deployment
Introduction to Spring Boot
Spring Boot is a powerful framework that simplifies the development of production-ready Spring applications. It provides auto-configuration, embedded servers, and a wide range of starter dependencies that make it easy to build enterprise-grade Java applications.
Why Choose Spring Boot?
Spring Boot offers several advantages for Java backend development:
- Auto-Configuration: Automatically configures Spring and third-party libraries
- Embedded Servers: Built-in Tomcat, Jetty, or Undertow servers
- Production Ready: Health checks, metrics, and externalized configuration
- No Code Generation: No XML configuration required
- Microservices Ready: Perfect for building microservices architectures
Getting Started with Spring Boot
Spring Boot applications can be created using Spring Initializr or manually. The framework provides a wide range of starter dependencies for common use cases like web development, data access, and security.
Project Setup
// pom.xml dependencies
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
// Main Application Class
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}Building REST APIs
Spring Boot makes it easy to build RESTful web services using Spring Web MVC. You can create controllers, handle HTTP requests, and return JSON responses with minimal configuration.
REST Controller Example
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = userService.findAll();
return ResponseEntity.ok(users);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = userService.findById(id);
if (user == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(user);
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User savedUser = userService.save(user);
return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
User updatedUser = userService.update(id, user);
if (updatedUser == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(updatedUser);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteById(id);
return ResponseEntity.noContent().build();
}
}Data Access with Spring Data JPA
Spring Data JPA provides a powerful abstraction over JPA, making it easy to work with databases. You can create repositories with custom query methods and leverage the power of JPA without writing boilerplate code.
Entity and Repository
// Entity
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String name;
@Column(name = "created_at")
private LocalDateTime createdAt;
// Constructors, getters, and setters
}
// Repository
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
List<User> findByNameContainingIgnoreCase(String name);
@Query("SELECT u FROM User u WHERE u.createdAt >= :date")
List<User> findUsersCreatedAfter(@Param("date") LocalDateTime date);
@Modifying
@Query("UPDATE User u SET u.name = :name WHERE u.id = :id")
int updateUserName(@Param("id") Long id, @Param("name") String name);
}
// Service Layer
@Service
@Transactional
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> findAll() {
return userRepository.findAll();
}
public Optional<User> findById(Long id) {
return userRepository.findById(id);
}
public User save(User user) {
user.setCreatedAt(LocalDateTime.now());
return userRepository.save(user);
}
public void deleteById(Long id) {
userRepository.deleteById(id);
}
}Security with Spring Security
Spring Security provides comprehensive security features for Spring applications. You can implement authentication, authorization, and protection against common security vulnerabilities.
Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults())
.csrf(csrf -> csrf.disable())
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
}
// JWT Token Provider
@Component
public class JwtTokenProvider {
private String secretKey = "mySecretKey";
private long validityInMilliseconds = 3600000; // 1h
public String createToken(String username, List<String> roles) {
Claims claims = Jwts.claims().setSubject(username);
claims.put("roles", roles);
Date now = new Date();
Date validity = new Date(now.getTime() + validityInMilliseconds);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(now)
.setExpiration(validity)
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
}
}Microservices with Spring Boot
Spring Boot is ideal for building microservices architectures. You can use Spring Cloud to implement service discovery, configuration management, and distributed tracing.
Service Discovery
// Application Properties
spring.application.name=user-service
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
eureka.instance.prefer-ip-address=true
// Main Application Class
@SpringBootApplication
@EnableEurekaClient
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
// Feign Client for Service Communication
@FeignClient(name = "order-service")
public interface OrderServiceClient {
@GetMapping("/api/orders/user/{userId}")
List<Order> getOrdersByUserId(@PathVariable Long userId);
@PostMapping("/api/orders")
Order createOrder(@RequestBody Order order);
}
// Using Feign Client in Service
@Service
public class UserService {
@Autowired
private OrderServiceClient orderServiceClient;
public UserWithOrders getUserWithOrders(Long userId) {
User user = userRepository.findById(userId).orElse(null);
List<Order> orders = orderServiceClient.getOrdersByUserId(userId);
return new UserWithOrders(user, orders);
}
}Testing Spring Boot Applications
Spring Boot provides excellent testing support with @SpringBootTest, @WebMvcTest, and @DataJpaTest annotations. You can write comprehensive unit and integration tests for your applications.
Testing Examples
// Integration Test
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase
class UserControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private UserRepository userRepository;
@Test
void testCreateUser() {
User user = new User("john@example.com", "John Doe");
ResponseEntity<User> response = restTemplate.postForEntity(
"/api/users", user, User.class);
assertEquals(HttpStatus.CREATED, response.getStatusCode());
assertNotNull(response.getBody().getId());
}
@Test
void testGetAllUsers() {
userRepository.save(new User("user1@example.com", "User 1"));
userRepository.save(new User("user2@example.com", "User 2"));
ResponseEntity<List> response = restTemplate.getForEntity(
"/api/users", List.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(2, response.getBody().size());
}
}
// Unit Test
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void testFindById() {
User user = new User("test@example.com", "Test User");
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
Optional<User> result = userService.findById(1L);
assertTrue(result.isPresent());
assertEquals("test@example.com", result.get().getEmail());
}
}Production Deployment
Spring Boot applications can be deployed using various methods including JAR files, Docker containers, and cloud platforms. The framework provides production-ready features like health checks and metrics.
Docker Configuration
# Dockerfile
FROM openjdk:11-jre-slim
WORKDIR /app
COPY target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=docker
- DATABASE_URL=jdbc:postgresql://db:5432/myapp
depends_on:
- db
db:
image: postgres:13
environment:
POSTGRES_DB: myapp
POSTGRES_USER: user
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:Best Practices
- Configuration: Use application.properties for environment-specific settings
- Error Handling: Implement global exception handling with @ControllerAdvice
- Logging: Use SLF4J with Logback for comprehensive logging
- Monitoring: Implement health checks and metrics with Actuator
- Security: Follow security best practices and keep dependencies updated
- Testing: Write comprehensive tests for all layers of your application
Conclusion
Spring Boot is a powerful framework for building enterprise-grade Java applications. Its auto-configuration, embedded servers, and extensive ecosystem make it ideal for both monolithic applications and microservices. With Spring Boot, you can focus on business logic while the framework handles the infrastructure concerns.