Spring Boot overview

Tong DuongTong Duong
10 min read

Spring Boot Introduction - DEV Community

I. Why Use Spring Boot?

1. Auto Configuration

  • Spring Boot automatically sets up your app based on the dependencies you add (in pom.xml or build.gradle).

  • No need for complex XML or manual Java config like in old Spring.

  • Saves time and reduces boilerplate code (code bắt buộc phải viết nhưng lặp lại và không mang nhiều giá trị logic)

2. Embedded Server

  • Comes with a built-in server (like Tomcat), so you don’t need to install a separate one.

  • You can run the app directly using main().

3. Starter Packages

  • Example: spring-boot-starter-web includes everything needed to build a web app.

  • You don’t need to add each dependency one by one.

4. Spring Boot = Spring + Auto Configuration + Embedded Server

  • It builds on Spring, but makes it faster and easier to develop apps.

🏷️ Important Annotations

@Configuration

  • Marks a class that defines beans (objects managed by Spring).

  • Often used with @Bean to register custom beans.

@EnableAutoConfiguration

  • Tells Spring Boot to auto-configure your app based on your dependencies and config files.

@ComponentScan

  • Tells Spring to look for @Component, @Service, @Repository, and register them automatically.

  • Enables dependency injection using @Autowired.

@SpringBootApplication

  • Combines:

    • @Configuration

    • @EnableAutoConfiguration

    • @ComponentScan

  • Most common annotation to start a Spring Boot app.

➡️ So if you use @SpringBootApplication, it’s the same as using all 3 above.


🌱 Profiles (Environments)

Use different settings for different environments (dev, test, prod, etc.)

  1. Set active profile in application.properties:

     spring.profiles.active=dev
    
  2. Create files for each profile:

  3. In code, use @Profile to load beans by environment:

     @Profile("dev")
     @Bean
     public DataSource devDataSource() {
         ...
     }
    

II. Dependency Injection & IoC Container

  1. Dependency Injection & IoC Container
  • Dependency Injection means Spring gives you the objects (beans) you need, instead of you creating them yourself.

  • IoC (Inversion of Control) Container is the part of Spring that creates and manages these objects.


  1. Bean & Component Scan
  • A bean is just a Java object created and managed by Spring.

  • Component scan means Spring looks for special annotations to find and register beans automatically.


  1. Common Annotations
  • @Component: Marks a class as a Spring bean.

  • @Service: Same as @Component, used for business logic classes.

  • @Repository: Same as @Component, used for data access classes.

  • @Controller: Handles web requests (returns HTML views).

  • @RestController: Like @Controller, but returns JSON (for APIs).


  1. Injecting Beans
  • @Autowired: Automatically inject a bean into a class.

  • @Qualifier: Use this when you have multiple beans of the same type, to choose one.

  • @Primary: Marks a bean as the default when multiple options exist.


  1. Bean Scopes
  • singleton (default): One shared instance in the entire app.

  • prototype: A new instance each time it’s requested.

  • request: One instance per HTTP request (web only).

  • session: One instance per user session (web only).


  1. Bean Lifecycle
  • @PostConstruct: Runs after the bean is created and dependencies are set.

  • @PreDestroy: Runs before the bean is removed.

  • InitializingBean: An interface with afterPropertiesSet() method, runs after injection

  • session: One instance per user session (web only).


III. Web Development (Spring Web MVC)

1. REST API Annotations

  • @RestController: Marks the class as a REST API controller. It returns data (like JSON), not HTML.

  • @RequestMapping: Maps HTTP requests to methods (can be used at class or method level).

  • @GetMapping: Handles GET requests (e.g., for fetching data).

  • @PostMapping: Handles POST requests (e.g., for sending or creating data).


2. PathVariable vs RequestParam

  • @PathVariable: Gets data from the URL path
    → Example: /user/{id}@PathVariable Long id

  • @RequestParam: Gets data from the query string
    → Example: /user?id=5@RequestParam Long id


3. Request & Response Body

  • @RequestBody: Converts JSON from the request into a Java object.

  • @ResponseBody: Converts Java object into JSON for the response. (Automatically used in @RestController)


4. Exception Handling

  • @ControllerAdvice: A class that handles exceptions globally (for all controllers).

  • @ExceptionHandler: Handles specific exceptions in a controller or in @ControllerAdvice.


5. Validation

  • @Valid / @Validated: Used to validate request data (usually in @RequestBody).

  • Hibernate Validator is the engine that performs the validation.

    • Common annotations:

      • @NotNull

      • @Size(min = 3, max = 10)

      • @Email

      • @Min, @Max

IV. Data Access


1. Spring Data JPA

  • A module in Spring that helps you access and manage databases using JPA (Java Persistence API).

  • It reduces boilerplate code by using interfaces to perform database operations.


2. Repository Interfaces

  • JpaRepository: Most commonly used. It includes CRUD, paging, and sorting methods.

  • CrudRepository: Basic CRUD (Create, Read, Update, Delete) operations.

  • You just define an interface, and Spring auto-implements it.


3. Custom Queries

  • @Query: Write custom SQL or JPQL queries inside repository methods.

      @Query("SELECT u FROM User u WHERE u.email = :email")
      User findByEmail(String email);
    
  • @Modifying: Used when the query changes data (INSERT, UPDATE, DELETE).


4. Pagination & Sorting

  • Built-in support using Pageable and Sort.

  • Example:

      Page<User> findAll(Pageable pageable);
    

5. Entity Mapping

  • @Entity: Marks a class as a JPA entity (maps to a database table).

  • @Table: (Optional) Specify the table name.

  • @Id: Marks the primary key field.

  • @GeneratedValue: Auto-generates the ID (e.g., auto-increment).


6. Transactions

  • @Transactional: Marks a method or class to run inside a transaction.

  • If an exception occurs, Spring can automatically roll back changes.

  • You can control rollback rules with settings like rollbackFor = Exception.class.


7. Database Initialization

  • schema.sql: SQL script to create tables (runs automatically on startup).

  • data.sql: SQL script to insert test/sample data.

  • Flyway / Liquibase: Tools to manage database schema changes (versioned migrations).


V. Spring Boot Security (Basic to Intermediate)


1. Spring Security Architecture

  • Spring Security is a framework to protect your app — it handles authentication (who you are) and authorization (what you can do).

  • It works by adding a chain of filters (called Security Filter Chain) that intercept every request.


2. Authentication / Authorization Flow

  • Authentication: Verifies identity (e.g., username & password).

  • Authorization: Checks if the user has permission to access a resource.

  • After logging in, Spring stores the user info in a SecurityContext.


3. Common Authentication Types

  • HTTP Basic: Sends username/password with every request (base64-encoded). Simple but not secure without HTTPS.

  • Form Login: Shows a login form (Spring provides default form, or you can customize).

  • JWT (optional): Uses JSON Web Token to send user data in a secure way (common in REST APIs, especially with frontend apps).


4. Security Configuration

  • Before Spring Security 6: Use WebSecurityConfigurerAdapter to override configure() method.

  • Spring Security 6 and newer: Use SecurityFilterChain bean with lambda-style configuration.

      @Bean
      public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
          return http
              .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
              .formLogin()
              .build();
      }
    

5. Method-Level Security

  • Used to protect specific methods (e.g., in services or controllers).

  • @PreAuthorize("hasRole('ADMIN')"): Only allow users with a specific role.

  • @Secured("ROLE_ADMIN"): Similar to @PreAuthorize, but simpler.

📝 Enable it with: @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)


6. CORS (Cross-Origin Resource Sharing)

  • CORS allows web apps on different domains (like React frontend at localhost:3000) to call your backend API.

  • In Spring Security, you need to enable CORS in the SecurityFilterChain or global config.

      http.cors().configurationSource(corsConfigurationSource());
    

VI. Configuration & Externalized Config


1. application.properties / application.yml

  • Spring Boot uses application.properties or application.yml to store app settings (like database config, server port, etc).

  • Example (YAML):

      server:
        port: 8081
    

2. Configuration Binding with @ConfigurationProperties

  • Binds a group of properties to a class.

  • Good for grouping related config.

  • Example:

      app:
        name: my-app
        timeout: 5000
    
      @Component
      @ConfigurationProperties(prefix = "app")
      public class AppConfig {
          private String name;
          private int timeout;
      }
    

3. @Value, @PropertySource, Environment Variables

  • @Value("${property.name}"): Inject a single value from properties or env.

  • @PropertySource("classpath:custom.properties"): Load extra property files.

  • Spring also reads environment variables automatically (useful for Docker, cloud, etc).


4. Profiles

  • Use profiles to define different configs for different environments (dev, test, prod).

  • @Profile("dev"): Bean or config only used in that profile.

  • Activate with:

      spring.profiles.active=dev
    

VII. Messaging & Integration (Optional – for senior/cloud-level knowledge)


1. Messaging with RabbitMQ & Kafka

  • RabbitMQ: Message queue system (based on AMQP). Good for task queues, job processing.

  • Kafka: Distributed event streaming platform. Good for high-throughput logs, real-time data.

  • Spring provides starters: spring-boot-starter-amqp (Rabbit), spring-kafka.

📌 Basic concepts:

  • Producer: Sends messages.

  • Consumer: Receives messages.

  • Queue / Topic: Where messages go.


2. Spring Integration or Apache Camel

  • Tools for connecting systems (file, HTTP, DB, messaging, etc.).

  • They use flows like: from → process → to.

📌 Example:

  • Receive a file → process it → send to API or message queue.

  • Apache Camel: Very flexible, uses RouteBuilder with from(...).to(...).

  • Spring Integration: Based on Spring, supports XML and Java DSL.


3. Event-Driven Architecture with Spring

  • Use events to decouple parts of the app.

  • @EventListener: Marks a method to listen for events.

  • ApplicationEventPublisher: Used to publish custom events.

📌 Example:

@Component
public class MyListener {
    @EventListener
    public void handle(MyEvent event) {
        // handle event
    }
}

applicationEventPublisher.publishEvent(new MyEvent(...));

VIII. Testing in Spring Boot


1. Test Annotations

  • @SpringBootTest: Loads the full application context. Used for integration tests.

  • @WebMvcTest: Loads only the web layer (e.g., controllers). Fast, good for testing APIs.

  • @DataJpaTest: Loads only the JPA/repository layer, uses an in-memory DB like H2 by default.


2. MockMvc

  • Used to test REST APIs without starting a real server.

  • Allows you to simulate HTTP requests like GET/POST and check responses.

mockMvc.perform(get("/api/users"))
       .andExpect(status().isOk())
       .andExpect(jsonPath("$.name").value("John"));

3. Mockito + JUnit 5

  • Mockito: Used to mock dependencies (e.g., services or repositories).

  • JUnit 5: Main testing framework (annotations like @Test, @BeforeEach, etc).

@Mock
UserService userService;

@InjectMocks
UserController userController;

4. Test Slice & Embedded Database

  • Test slice: Spring loads only part of the app for faster tests (@WebMvcTest, @DataJpaTest, etc).

  • Embedded DB: Like H2, is used in tests for isolation (no need for a real DB).

spring:
  datasource:
    url: jdbc:h2:mem:testdb

IX. Spring Boot Actuator

Spring Boot Actuator helps you monitor and manage your application by exposing useful endpoints (like health checks, metrics, etc.).


1. Common Actuator Endpoints

  • /actuator/health: Shows app health (UP/DOWN).

  • /actuator/metrics: Shows system metrics (e.g. memory, CPU, request count).

  • /actuator/info: Shows custom app info (e.g. version, contact).

🛠️ Enable them in application.properties:

propertiesCopyEditmanagement.endpoints.web.exposure.include=health,info,metrics

2. Custom Health Indicators

You can create your own health checks (e.g., check DB, external service).

@Component
public class MyServiceHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        boolean isOk = checkSomething();
        return isOk ? Health.up().build() : Health.down().withDetail("error", "Something is wrong").build();
    }
}

3. Securing Actuator Endpoints

By default, some endpoints (like /shutdown) are protected or disabled.

To secure them:

management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=when-authorized

Add Spring Security and secure the endpoints:

http
  .requestMatcher(EndpointRequest.toAnyEndpoint())
  .authorizeRequests(auth -> auth.anyRequest().hasRole("ADMIN"))
  .httpBasic();

X. Build & Deploy in Spring Boot


1. Spring Boot Packaging: JAR vs WAR

  • JAR (default): Spring Boot creates a standalone app with an embedded server (like Tomcat). You can run it directly with java -jar app.jar.

  • WAR: Used if you want to deploy the app to an external server (like a traditional Tomcat server). Requires a bit more setup.

✅ Use JAR for most modern deployments (Docker, cloud, etc).


2. Build Tool: Maven or Gradle

  • Both are used to manage dependencies and build your project.

  • Maven: XML-based (pom.xml). More widely used in enterprises.

  • Gradle: Groovy/Kotlin-based (build.gradle). Faster and more flexible.

🛠️ Use either based on your team's preference.


3. Dockerize Spring Boot App

Steps to run Spring Boot inside a Docker container:

Dockerfile example:

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

Then:

docker build -t my-app .
docker run -p 8080:8080 my-app

4. Run with Profiles, Env Variables, Config Server

  • Use profiles for different environments (dev, test, prod):
java -jar app.jar --spring.profiles.active=prod
  • Use environment variables to pass configs (e.g., DB URL, secrets):
SPRING_DATASOURCE_URL=... java -jar app.jar
  • Use Spring Cloud Config Server to load config from Git or other sources (for microservices setups).

0
Subscribe to my newsletter

Read articles from Tong Duong directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tong Duong
Tong Duong