๐Ÿงฐ Spring Boot Advanced Features: Security, Testing, and Deployment Strategies

Welcome back to The Code Hut! ๐Ÿš€ In this post, we’ll take your Spring Boot skills to the next level — exploring security, testing, and deployment strategies that turn great apps into production-ready systems. ๐Ÿ’ช

1. ๐Ÿ”’ Spring Security Essentials

Spring Security provides powerful authentication and authorization mechanisms out of the box.

  • Authentication: Verifies user identity.
  • Authorization: Grants access to resources based on roles or authorities.
  • Security Filters: Intercept and process requests using a filter chain.

// Basic in-memory authentication
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("admin").password("{noop}password").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
                .antMatchers("/api/public").permitAll()
                .antMatchers("/api/admin").hasRole("ADMIN")
            .and()
            .httpBasic();
    }
}
  • ๐Ÿ’ก Use BCryptPasswordEncoder for encrypted passwords.
  • ๐Ÿ”‘ Use JWT for stateless authentication in distributed systems.

2. ๐Ÿงช Testing in Spring Boot

Spring Boot integrates testing seamlessly with JUnit 5 and Spring Test modules.

๐Ÿ”น Test Annotations

  • @SpringBootTest — loads full application context.
  • @WebMvcTest — test only controller layer.
  • @DataJpaTest — test JPA repositories.
  • @MockBean — inject mock dependencies into Spring context.

// Example: Testing a Controller
@WebMvcTest(UserController.class)
class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    void shouldReturnUser() throws Exception {
        when(userService.getUser(1L)).thenReturn(new User(1L, "Alice"));
        
        mockMvc.perform(get("/users/1"))
               .andExpect(status().isOk())
               .andExpect(jsonPath("$.name").value("Alice"));
    }
}

3. ๐Ÿงฑ Profiles & Configuration Management

Spring Boot supports multiple configuration environments using @Profile and application-{profile}.yml files.

  • @Profile("dev") — load beans only in the dev environment.
  • Activate profiles via spring.profiles.active=prod.
  • Externalize secrets and configuration using environment variables or Vault.

# application-dev.yml
server:
  port: 8080
spring:
  datasource:
    url: jdbc:h2:mem:devdb
---
# application-prod.yml
server:
  port: 8081
spring:
  datasource:
    url: jdbc:postgresql://prod-db:5432/app

4. ๐Ÿงฐ Observability: Actuator & Metrics

Spring Boot Actuator provides production-ready features like health checks and metrics.

  • ๐Ÿฉบ Health Checks: /actuator/health
  • ๐Ÿ“Š Metrics: /actuator/metrics
  • ๐Ÿง  Info Endpoint: /actuator/info

management:
  endpoints:
    web:
      exposure:
        include: health, info, metrics

5. ๐Ÿณ Deployment Strategies

Modern Spring Boot apps can be deployed easily across different environments.

๐Ÿ”น Docker


# Dockerfile
FROM openjdk:17-jdk-slim
COPY target/app.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

๐Ÿ”น CI/CD Integration

  • Use GitHub Actions, Jenkins, or GitLab CI for automated build/test/deploy.
  • Push Docker images to container registries (ECR, GCR, Docker Hub).
  • Deploy on Kubernetes, ECS, or Cloud Run for scalability.

๐Ÿ”น Cloud Configuration

Use Spring Cloud Config Server for centralized management — we’ll cover this in the next post.

6. ⚡ Summary Table

Concept Purpose Example / Notes
Spring Security Authentication and authorization Supports JWT, OAuth2, LDAP, Basic
Testing Layered testing with @WebMvcTest, @DataJpaTest JUnit 5 + Mockito
Profiles Environment-specific configuration application-dev.yml, application-prod.yml
Actuator Health, metrics, info endpoints Expose only required endpoints in production
Deployment Containerize & automate pipelines Docker, CI/CD, Kubernetes

7. ๐Ÿš€ Final Thoughts

With Spring Boot’s advanced features, you can create secure, testable, and deployable applications with ease. Combine these with Spring Cloud to move toward scalable distributed systems — which we’ll explore in the next post! ☁️

Next in the Series

In the next post, we’ll explore Spring Cloud Explained: Distributed Systems Made Simple

Labels: Spring Boot, Spring Security, Testing, JUnit 5, Mockito, Profiles, CI/CD, Docker, Actuator, Cloud Config, Kubernetes, DevOps

Comments

Popular posts from this blog

๐Ÿ› ️ The Code Hut - Index

๐Ÿ›ก️ Resilience Patterns in Distributed Systems

๐Ÿ›ก️ Thread-Safe Programming in Java: Locks, Atomic Variables & LongAdder