Master Spring Boot: From Basics to Advanced Annotations and Best Practices

This comprehensive guide explains what Spring Boot is, why it was created for micro‑service development, how it simplifies configuration with starters and auto‑configuration, and provides detailed coverage of core annotations, configuration files, security, CORS, transaction management, and deployment options for Java backend developers.

Intelligent Backend & Architecture
Intelligent Backend & Architecture
Intelligent Backend & Architecture
Master Spring Boot: From Basics to Advanced Annotations and Best Practices

What is Spring Boot?

Spring Boot is a sub‑project of the Spring ecosystem that does not replace Spring’s core features but tightly integrates with it to improve developer experience. It offers a one‑stop solution that simplifies configuration, provides starter dependencies, embeds a servlet container, and enables rapid project setup.

Why Spring Boot was created

The rise of micro‑services highlighted the limitations of monolithic applications, which require extensive XML or Java configuration for each component. Spring Boot emerged to address this by offering convention‑over‑configuration, auto‑configuration, and zero‑configuration integration of common libraries such as Redis, MongoDB, JPA, and Kafka.

Microservices diagram
Microservices diagram

How to create a Spring Boot project

The recommended way is to use Spring Initializr : select the build tool, language, Spring Boot version, project name, and dependencies, then generate a zip file that can be imported directly into an IDE.

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Key advantages of Spring Boot

Quickly create standalone Spring projects with embedded containers.

Starters manage dependency versions automatically.

Extensive auto‑configuration reduces boilerplate.

No XML configuration required; everything can be done with Java or YAML.

Production‑ready monitoring and health checks.

Seamless integration with cloud platforms.

Core configuration files

Spring Boot uses two main configuration files: bootstrap.yml / bootstrap.properties (parent context, loaded first, often used with Spring Cloud) and application.yml / application.properties (application context). The bootstrap context has higher precedence and cannot be overridden by the application context.

Configuration loading order

Properties are loaded in a defined precedence, from highest to lowest: DevTools global settings, @TestPropertySource, @SpringBootTest, command‑line arguments, SPRING_APPLICATION_JSON, servlet init parameters, JNDI, system properties, OS environment variables, random values, external config files, internal config files, @PropertySource, and finally default values.

YAML vs properties

YAML is a human‑readable hierarchical format that supports arrays and nested structures, making complex configurations clearer than flat property files. However, YAML cannot be imported with @PropertySource.

XML configuration support

Although Java‑based configuration is preferred, Spring Boot can still import XML files using @ImportResource when necessary.

Core annotations

The central annotation is @SpringBootApplication, which combines @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan. Other essential annotations include @Controller, @RestController, @RequestMapping, @GetMapping, @PostMapping, @PathVariable, @RequestParam, @Autowired, @Service, @Repository, @Entity, @Bean, @Scope, @Transactional, and @ControllerAdvice for global exception handling.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {}

Running Spring Boot

Spring Boot applications can be run by executing the packaged jar ( java -jar app.jar), using Maven/Gradle plugins, or directly invoking the main method from an IDE.

Auto‑configuration principle

The @EnableAutoConfiguration annotation loads auto‑configuration classes listed in META-INF/spring.factories. Each auto‑configuration class is conditional on the presence of specific classes or properties, allowing Spring to configure beans automatically.

Spring Profiles

Profiles (e.g., dev, test, prod) enable selective bean registration and configuration loading, allowing environment‑specific settings such as enabling Swagger only in QA.

Custom port

Set server.port=8090 in application.properties to run the application on a non‑default port.

Security

Add spring-boot-starter-security and extend WebSecurityConfigurerAdapter to secure endpoints with minimal code.

CORS and CSRF

Implement CORS globally by creating a WebMvcConfigurer bean:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
                .maxAge(3600);
    }
}

CSRF attacks can be mitigated by enabling Spring Security’s CSRF protection.

Starters

Starters are meta‑dependencies that bundle commonly used libraries. For example, spring-boot-starter-data-jpa brings in JPA, Hibernate, and a connection pool. Custom starters follow the spring-boot-starter-* naming convention.

Enabling features

To inherit the default dependency management, extend spring-boot-starter-parent or import spring-boot-dependencies via <dependencyManagement>. Override versions by defining properties such as slf4j.version in the <properties> section.

Spring Boot jar

The packaged jar is executable (run with java -jar) and contains a BOOT-INF/classes directory. It cannot be used as a regular library jar unless a separate non‑executable jar is produced.

Common annotations reference

Key annotations include: @SpringBootApplication – entry point. @RestController – combines @Controller and @ResponseBody. @RequestMapping, @GetMapping, @PostMapping – map HTTP requests. @PathVariable, @RequestParam, @RequestHeader, @CookieValue – bind request data. @Service, @Repository, @Component – component stereotypes. @Autowired – dependency injection. @Transactional – declarative transaction management. @ControllerAdvice and @ExceptionHandler – global exception handling.

Transaction management

Spring supports both programmatic ( TransactionTemplate) and declarative ( @Transactional) transaction management, with the latter being the preferred approach.

Global exception handling

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleException() {
        return "Exception Deal!";
    }
}

Conclusion

Spring Boot dramatically reduces the complexity of building Java enterprise applications by providing auto‑configuration, starter dependencies, embedded containers, and extensive tooling, allowing developers to focus on business logic rather than boilerplate configuration.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaMicroservicesBackend DevelopmentConfigurationSpring Bootannotations
Intelligent Backend & Architecture
Written by

Intelligent Backend & Architecture

We share personal insights on intelligent, automated backend technologies, along with practical AI knowledge, algorithms, and architecture design, grounded in real business scenarios.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.