Comprehensive Overview of Spring Boot: Features, Core Annotations, Configuration, and Best Practices
This article provides a detailed introduction to Spring Boot, covering its purpose, advantages, core @SpringBootApplication annotation, supported logging frameworks, starter mechanism, new features in version 2.x, configuration methods, security, CORS handling, actuator monitoring, hot deployment, multi‑datasource setup, session sharing, and packaging differences, all aimed at helping developers quickly adopt and master the framework.
1. What is Spring Boot?
Spring Boot is a sub‑project of the Spring open‑source organization that offers a one‑stop solution for Spring components, simplifying usage by reducing heavy configuration and providing various starters for rapid development.
2. Why use Spring Boot?
It enables fast development, quick integration, simplified configuration, and includes an embedded service container.
3. Spring Boot vs. Spring Cloud
Spring Boot is a rapid‑development framework, while Spring Cloud is a full micro‑service framework that depends on Spring Boot.
4. Advantages of Spring Boot
Easy to learn, improves development efficiency, and offers a faster, simpler development framework for Spring.
Out‑of‑the‑box, avoids cumbersome configuration.
Provides common non‑business features such as embedded servers, security management, runtime monitoring, health checks, and externalized configuration.
Overall, it simplifies coding, configuration, deployment, and monitoring.
5. Core Annotation of Spring Boot
The main annotation on the startup class is @SpringBootApplication, which combines three annotations:
@SpringBootConfiguration: aggregates @Configuration to enable configuration file functionality.
@EnableAutoConfiguration: enables automatic configuration and allows disabling specific auto‑configurations, e.g., @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) .
@ComponentScan: scans Spring components.
6. Supported Logging Frameworks
Spring Boot supports Java Util Logging, Log4j2, and Logback. When using starters, Logback is the default, and any of these can be configured to output to console or files.
7. How Spring Boot Starters Work
Starters are collections of dependencies. During startup, the @SpringBootApplication annotation reads each starter’s spring.factories file, which lists beans to be created and auto‑configured in the Spring context.
SpringContext is the configuration file of Spring.
8. New Features in Spring Boot 2.x vs. 1.x
Configuration changes
JDK version upgrade
Third‑party library upgrades
Reactive Spring support
HTTP/2 support
Configuration property binding
Various improvements and enhancements
9. Front‑end Templates Supported
Thymeleaf, FreeMarker, JSP (officially not recommended due to limitations).
10. Drawbacks of Spring Boot
Generally few drawbacks; the main issue is that reduced manual configuration can make error diagnosis harder.
11. Ways to Run Spring Boot
Package with a command or run in a container.
Use Maven/Gradle plugins.
Execute the main method directly.
12. Does Spring Boot Need an External Container?
No, it embeds Tomcat, Jetty, etc.
13. Ways to Enable Spring Boot Features
Inherit from spring-boot-starter-parent project.
Import spring-boot-dependencies as a dependency.
14. Hot Deployment Options
Template hot deployment, spring-boot-devtools, Spring Loaded, JRebel.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>15. Transaction Management
Add @EnableTransactionManagement on the startup class and annotate public methods or classes with @Transactional.
16. Asynchronous Calls
Use @Async on methods and enable it with @EnableAsync in the startup class.
@Configuration
// Scan for @Async annotations
@EnableAsync
public class AsyncConfiguration {
}17. Running Code at Startup
Implement ApplicationRunner or CommandLineRunner, both providing a single run method.
18. Configuration Loading Methods
Use @PropertySource, @Value, @Environment, or @ConfigurationProperties to bind variables.
19. What is JavaConfig?
JavaConfig replaces XML configuration with pure Java classes, offering object‑oriented configuration, inheritance, type safety, and easier refactoring.
@Configuration : marks a class as a configuration source.
@ComponentScan : scans the package for components (equivalent to <context:component-scan/>).
@Bean : defines a bean (equivalent to XML <bean>).
@EnableWebMvc : enables Spring MVC (equivalent to <mvc:annotation-driven/>).
@ImportResource : imports XML resources.
20. Auto‑Configuration Principle
The core @SpringBootApplication includes @EnableAutoConfiguration, which reads possible auto‑configuration classes from META-INF/spring.factories, filters them by @Conditional, and applies them unless excluded.
21. Configuration Loading Order
Properties files
YAML files
System environment variables
Command‑line arguments
22. What is YAML?
YAML is a human‑readable data‑serialization language commonly used for configuration files, offering hierarchical structure and less confusion than properties files.
23. Advantages of YAML
Preserves order, is concise, supports arrays of primitives or objects, but cannot be imported with @PropertySource.
24. Using XML Configuration in Spring Boot
Spring Boot prefers Java configuration, but XML can be imported via @ImportResource.
25. Core Configuration Files
bootstrap.properties(or .yml) is loaded by the parent ApplicationContext and takes precedence, mainly used with Spring Cloud; application.properties (or .yml) is loaded by the ApplicationContext for standard Boot configuration.
26. Spring Profiles
Profiles allow environment‑specific configuration files (e.g., dev, test, prod) and bean registration based on the active profile.
spring:
profiles:
active: dev27. Multi‑DataSource Strategy
Configure multiple data sources in properties, use @ConfigurationProperties to read them, and register mappers with @MapperScan for each package.
28. Multi‑DataSource Transaction Management
Specify a transaction manager in the service layer with @TransactionManager or use JTA/Atomikos for distributed transactions.
29. Securing Spring Boot Applications
Use HTTPS in production.
Scan dependencies with Snyk.
Upgrade to the latest version.
Enable CSRF protection.
Apply Content‑Security‑Policy to prevent XSS.
30. Implementing Security
Add the spring-boot-starter-security dependency and extend WebSecurityConfigurerAdapter to configure security.
31. Spring Security vs. Shiro
Spring Security is heavyweight; Shiro is lightweight.
Spring Security has a complex concept and configuration; Shiro is simpler.
Spring Security is feature‑rich; Shiro offers basic features.
32. Solving CORS Issues
Implement WebMvcConfigurer and override addCorsMappings to allow cross‑origin requests.
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("*")
.allowedMethods("*")
.maxAge(1800)
.allowedOrigins("*");
}
}33. Spring Boot Actuator
Actuator provides production‑ready endpoints for monitoring application health, metrics, and other status information via HTTP.
34. Global Exception Handling
Use @ControllerAdvice together with @ExceptionHandler to capture and process exceptions globally.
@Slf4j
@ControllerAdvice
public class GlobalExceptionAdvice {
@ExceptionHandler({Exception.class})
@ResponseBody
public Object handleException(HttpServletRequest request, Exception e) throws Exception {
log.error(e.getMessage(), e);
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
throw e;
}
HashMap<String, Object> map = new HashMap<>();
map.put("message", "Global exception: " + e.getMessage());
return map;
}
}35. Monitoring Multiple Microservices
Use Spring Boot Admin (built on Actuator) to visualize metrics of many services via a web UI.
36. Performance Optimization
Reduce annotation scanning by replacing @SpringBootApplication with explicit @EnableAutoConfiguration and @Configuration, switch the embedded container from Tomcat to Undertow, and perform JVM tuning.
37. Hot Reload / DevTools
Include the spring-boot-devtools dependency to automatically restart the embedded server on code changes, improving developer productivity.
38. Session Sharing in Microservices
Use Spring Session with Redis to store session data centrally, allowing multiple services to share the same session transparently.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>39. Common Starter Dependencies
spring-boot-starter-web– embedded Tomcat and web support. spring-boot-starter-data-jpa – JPA database support. spring-boot-starter-data-redis – Redis support. spring-boot-starter-data-solr – Solr support. mybatis-spring-boot-starter – MyBatis integration.
40. What is a Spring Boot Starter?
A starter provides an auto‑configuration class (e.g., XXXAutoConfiguration) that uses conditional annotations to activate defaults, while allowing developers to override properties via type‑safe configuration.
41. Implementing Scheduled Tasks
Use the @Scheduled annotation for simple scheduling or integrate Quartz for advanced job scheduling.
42. Purpose of spring-boot-starter-parent
Sets Java version to 1.8.
Uses UTF‑8 encoding.
Inherits dependency versions from spring-boot-dependencies.
Configures packaging, resource filtering, and plugins.
Manages profile‑specific application‑*.properties and application‑*.yml files.
In short, it is used for packaging.
43. How to Package a Spring Boot Project
Run mvn clean package in the project directory (or use the Maven tool window to execute clean then package).
44. Difference Between Spring Boot Executable JAR and Regular JAR
An executable JAR can be run with java -jar xxx.jar and contains classes under BOOT-INF/classes, making it unsuitable for direct dependency by other projects unless repackaged.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
