SpringBoot
Li Wei
SpringBoot
Overview
SpringBoot offers a fast way to use Spring. Based on the principle of convention over configuration, it lets developers focus entirely on writing business logic without constantly switching between configuration and code, greatly improving development efficiency.
SpringBoot features:
- Auto‑configuration – a runtime (more precisely, application‑startup) process that selects which configuration to apply based on many factors. SpringBoot handles this automatically.
- Starter dependencies – essentially Maven Project Object Models (POMs) that declare transitive dependencies needed for a particular feature. In short, a starter bundles the coordinates for a specific capability and provides sensible defaults.
- Auxiliary features – common non‑functional capabilities for large projects such as embedded web servers, security, metrics, health checks, externalized configuration, etc.
Auto‑Configuration
Dependency Management
The spring-boot-starter-parent defines version information for a wide range of technologies, providing an optimal combination of versions. Each starter lists the coordinates required for its functionality, most of which inherit version numbers from the parent project. By inheriting the parent and adding a starter, you obtain the necessary JARs through transitive dependency resolution without version conflicts, thanks to SpringBoot’s automatic version mediation.
How It Works
SpringBoot’s auto‑configuration mechanism:
- The main class of a SpringBoot project is annotated with
@SpringBootApplication, which bundles three annotations:@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan
- Among them,
**@EnableAutoConfiguration**is the core annotation that enables auto‑configuration. It imports the appropriate configuration selectors via the**@Import**annotation. Internally, it reads the META-INF/spring.factories file found on the classpath of the project and its dependent JARs. The fully‑qualified class names listed there are loaded, and the beans defined in those configuration classes are conditionally registered in the Spring container based on the conditions specified by their conditional annotations. - Condition checks use annotations such as
**@ConditionalOnClass**, which verify the presence of a particular class. If the class exists, the configuration class is loaded and all its beans become available in the Spring container.
Core Annotations
@SpringBootApplication
@SpringBootApplication – the primary annotation that enables SpringBoot’s auto‑deployment.
- Parameter
scanBasePackages– allows you to specify the packages to scan. - By default, it scans the package of the main class and its sub‑packages.
If the main package is com.example.springbootenable and you need to scan com.example.config, you have three options:
- Use
@ComponentScanto scan thecom.example.configpackage. - Use the
@Importannotation to load classes; Spring will instantiate them and place them in the IoC container, using the fully‑qualified class name as the default bean name. - Wrap the
@Importannotation.
Example:
UserConfig
EnableUser annotation class
@Configuration
@Configuration – marks the class as a SpringBoot configuration class.
proxyBeanMethods = true(Full mode) – every@Beanmethod is called once; the returned component is a singleton (the default). Bean methods can depend on each other, and the container resolves those dependencies.proxyBeanMethods = false(Lite mode) – each@Beanmethod call creates a new instance; beans are independent, which speeds up container startup.
@Conditional
A conditional annotation introduced after Spring 4.0. By implementing the Condition interface, you can load beans only when certain conditions are met.
- Annotation:
@Conditional - Purpose: Conditional bean registration. Apply it to a method or class; the scope differs accordingly.
- Usage: Combine
@Conditionalwith an implementation ofCondition(e.g.,ClassCondition).
ConditionContext API:
| Method | Description |
|---|---|
ConfigurableListableBeanFactory getBeanFactory() |
Obtain the BeanFactory used by the IoC container |
ClassLoader getClassLoader() |
Get the class loader |
Environment getEnvironment() |
Access current environment information |
BeanDefinitionRegistry getRegistry() |
Retrieve the bean definition registry |
Code example:
ClassConditionUserConfig- Main application class
Custom annotations can make the class‑presence check dynamic, allowing you to decide at runtime which bytecode files exist.
Common conditional annotations provided by SpringBoot:
@ConditionalOnProperty– initialize a bean only if a specific property and value exist in the configuration file.@ConditionalOnClass– initialize a bean only if a particular class is present on the classpath.@ConditionalOnMissingClass– same as above (duplicate entry in source).@ConditionalOnMissingBean– initialize a bean only if a specific bean is not already defined.
@ImportResource
Import an XML configuration file (e.g., bean.xml). If you still need to reuse bean.xml, simply use @ImportResource to import it.
@ConfigurationProperties
@ConfigurationProperties – binds properties from a .properties or .yml file to a JavaBean.
Code example:
- Configuration file
- Corresponding JavaBean class
Event Listeners
During startup, SpringBoot invokes several listeners: ApplicationContextInitializer, SpringApplicationRunListener, CommandLineRunner, and ApplicationRunner. Implement any of these interfaces to perform actions when the application starts.
- MyApplicationRunner – runs after the application has started. Register it in the container with
@Component. - MyCommandLineRunner
- MyApplicationContextInitializer – enable by adding
META-INF/spring.factoriesundersrc/main/resources. - MySpringApplicationRunListener – requires a constructor implementation.
Configuration Files
How to Configure
File Types
SpringBoot follows conventions and provides sensible defaults. To override defaults, use application.properties or application.yml (also accepted as application.yaml).
- Default file name:
application - Priority (higher overrides lower) when files are in the same directory: properties > yml > yaml
Example – changing the embedded Tomcat port:
application.propertiesapplication.ymlapplication.yaml
Loading Order
All configuration files found in the various locations are loaded; higher‑priority sources override lower‑priority ones.
Search order from highest to lowest priority:
file:./config/–/configdirectory inside the current projectfile:./– project root directoryclasspath:/config/–/configdirectory on the classpathclasspath:/– classpath root (src/main/resources)
External configuration files are loaded after internal ones, allowing you to supplement or override them.
- Command line – after packaging, run the JAR from the
targetdirectory and specify the config location or use command‑line arguments to set the order of precedence.
YAML Syntax
Basic rules:
- Case‑sensitive.
- A space must precede every data value (acts as a delimiter).
- Indentation denotes hierarchy; do not use tabs, only spaces (tab width varies across editors and can break the structure).
- The exact number of spaces is irrelevant as long as elements at the same level align.
''#"denotes a comment; everything from this token to the end of the line is ignored by the parser.
Data structures:
- Scalar – a single, indivisible value.
- Object – a collection of key‑value pairs (Map, Hash).
- Array – an ordered list of values (List, Array).
- Note: JSON is discouraged; use native YAML syntax instead.
Accessing Configuration
Three ways to read configuration values:
- Annotation
@Value Environmentobject- Annotation
@ConfigurationPropertiestogether with@Component
Important: The prefix attribute must always be specified.
IDE Assistance
Custom classes bound to configuration files usually lack code completion. Adding the following dependency enables suggestions:
(dependency snippet omitted)
@Profile
@Profile – specifies the environment(s) in which a component should be registered. Without a profile, the bean is loaded in all environments.
- Beans annotated with a profile are only registered when that profile is active; the default profile is
default. - Placing
@Profileon a configuration class makes the entire class active only when the specified profile is enabled. - Beans without a profile are always loaded.
Profile configuration:
- Profiles enable dynamic switching of configurations for different environments.
- Multiple‑file approach: create separate files for each environment:
application-dev.properties/application-dev.yml– developmentapplication-test.properties/application-test.yml– testingapplication-pro.properties/application-pro.yml– production
- Multi‑document YAML: separate documents with
---.
Activating a profile:
- In a configuration file: set
spring.profiles.active=…. - JVM argument:
-Dspring.profiles.active=…(set in VM options). - Command‑line argument:
--spring.profiles.active=…(can be passed when running the packaged JAR).
Web Development
Supported Features
SpringBoot auto‑configures many conventions, so most scenarios require no custom setup.
- Content‑Negotiating View Resolver (
ContentNegotiatingViewResolver) and BeanName view resolver (BeanNameViewResolver) - Static resources (including WebJars) and a default
index.html - Automatic registration of converters, generic converters, and formatters
- Content‑negotiation handlers (
HttpMessageConverters) - Internationalization via
MessageCodesResolver
Development guidelines:
- Use
@Configuration+WebMvcConfigurerfor custom rules; avoid@EnableWebMvcannotations. - Declare an implementation of
WebMvcRegistrationsto replace default low‑level components. - Combine
@EnableWebMvc,@Configuration, andDelegatingWebMvcConfigurationto take full control of Spring MVC.
Static Resources
Access Rules
Default static resource locations are on the classpath, with precedence (high to low): /META-INF/resources, /resources, /static, /public. / refers to the root of the current project.
Static mapping /** means a request to / + 静态资源名 is served directly from the default static locations. The request flow is: first try a controller; if none matches, fall back to the static resource handler; if still not found, return a 404.
- Change the default resource location – modify the static resource prefix (default is
/**).
Access URL:http://localhost:8080/resources/+ resource name – this effectively re‑maps all resources to/resources/. - WebJar resources – e.g.,
http://localhost:8080/webjars/jquery/3.5.1/jquery.js(path follows the JAR’s internal structure).
Welcome Page
An index.html placed in a static resource directory is served as the welcome page at http://localhost:8080. The welcome‑page feature cannot change the URL prefix. To customize the small icon shown on browser tabs, place a file named favicon.ico in the static resources directory.
Source‑Code Insight
- Auto‑configuration class for Spring MVC:
WebMvcAutoConfiguration- Inner class:
WebMvcAutoConfigurationAdapter ResourceProperties resourceProperties– obtains objects bound tospring.resources
- Inner class:
WebMvcProperties mvcProperties– obtains objects bound tospring.mvcListableBeanFactory beanFactory– Spring’sBeanFactoryHttpMessageConverters– finds allHttpMessageConvertersResourceHandlerRegistrationCustomizer– locates customizers for resource handlersDispatcherServletPath– project pathServletRegistrationBean– registersServletandFilterfor the applicationWebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.addResourceHandler()– two static‑resource mapping strategiesWebMvcAutoConfiguration.EnableWebMvcConfiguration.welcomePageHandlerMapping()– welcome page
WelcomePageHandlerMapping– accessing/reachesindex.html.
REST Mapping
- Enable REST support.
- Source analysis shows that
HiddenHttpMethodFilteris injected to handle REST‑style HTTP methods.
Embedded Containers
SpringBoot provides an embedded servlet container; supported WebServer implementations include Tomcat, Jetty, and Undertow.
Configuration steps:
- When a web application starts, SpringBoot pulls in the web‑scenario starter (e.g., Tomcat) and creates a web‑aware IoC container.
SpringApplication.run(BootApplication.class, args)– application startupConfigurableApplicationContext.run()context = createApplicationContext()– create containerapplicationContextFactory = ApplicationContextFactory.DEFAULTapplicationContextFactory.create(this.webApplicationType)– create container based on application type
refreshContext(context)– container refresh/startup
Embedded container workflow:
During Spring container startup, before instantiating non‑lazy singleton beans, a method onRefresh() is called. Subclasses override this method; the web container overrides it to create the WebServer.
(content truncated)
Originally written by Li Wei (李唯_) and published in Chinese on 后端技术栈全书 (Full-Stack Backend Engineering). Translated and adapted for DriftSeas with permission.