Spring Boot

The first Spring Boot application
The goal is to return Hello World from the server when the browser accesses the specified address.
Create a project and introduce dependencies
You can create projects through Spring Initializr. The following example uses Spring Boot 3.3.4, so the running environment requires at least Java 17.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.4</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>Write controller
@RestController
public class HelloController {
@GetMapping("/test")
public String test() {
return "Hello World";
}
}
After starting the project and visiting http://localhost:8080/test, the browser will display Hello World.
Packaging and deployment
Configure Maven plug-ins
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Generating executable JAR
Execute in the project root directory:
mvn clean package
After the build is successful, you can find the JAR file in the target directory.
run the project
java -jar target/项目名称.jar
The core mechanism of Spring Boot
Parent project and dependency management

spring-boot-starter-parent provides common Maven configurations and inherits Spring Boot’s dependency management capabilities.

Spring Boot uniformly manages a large number of commonly relied versions. When introducing managed dependencies, versions are usually not required to be declared separately, reducing the probability of version conflicts.
Starter Scene Launcher
spring-boot-starter-web is a Web scenario initiator that introduces related dependencies such as Spring MVC, JSON processing, and default embedded servers.
If you need to replace the default Tomcat with Jetty, you can exclude Tomcat and introduce Jetty:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>Startup class and SpringApplication.run()
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext =
SpringApplication.run(SpringBootDemoApplication.class, args);
System.out.println(applicationContext.getBean(HelloController.class));
}
}SpringApplication.run() launches the Spring container, performs automatic configuration, and launches the embedded server in the Web project.
@SpringBootApplication
@SpringBootApplication is a combination annotation, which mainly contains the following capabilities:
@SpringBootConfiguration: Indicates that the current class is a Spring Boot configuration class, which essentially has the function of@Configuration.@EnableAutoConfiguration: Automatic configuration based on dependencies, existing beans and configuration attributes in the classpath.@ComponentScan: The default scan for the package where the boot class is located and its subpackages.
Therefore, controllers, business classes, configuration classes, etc. should usually be placed in the package in which the startup class is located or in its subpackages. If the package structure does not meet the default scan range, the scan path needs to be explicitly configured.
automatic configuration
Automatic configuration does not unconditionally register all beans. Spring Boot combines dependencies, configuration properties, and beans existing in the container to determine whether a configuration takes effect.
For example, after the introduction of Web Starter, Spring Boot configures components such as DispatcherServlet, request mapping, and message converter for Spring MVC applications. When a developer declares a Bean of the same type himself, some automatic configurations will be subject to conditions.
profile
Spring Boot supports application.properties and application.yml by default. YAML expresses hierarchy through indentation, which must use spaces and cannot use tabs.

person:
last-name: tom
age: 20
married: false
birth: 1995-03-23
maps:
name1: jack
name2: rose
friends:
- zhangsan
- lisi
dog:
name: dog
age: 2Using @ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Boolean married;
private LocalDate birth;
private Map<String, String> maps;
private List<String> friends;
private Dog dog;
// getter 和 setter
}@ConfigurationProperties is suitable for batch binding of configurations under the same prefix. Attribute names support loose binding. For example, last-name in configuration can be bound to Java attribute lastName.
For configuration classes, you can also register with @ConfigurationPropertiesScan or @EnableConfigurationProperties without adding @Component to the configuration object.
@Value, @PropertySource and @ImportResource
- The
@Valueis suitable for reading a small number of independent configurations. @PropertySourcecan load additional.propertiesfiles, but does not directly support YAML.@ImportResourcecan import traditional Spring XML configurations.
multiple environment configuration
Spring Boot uses Profiles to manage configuration in different environments.
multi-file method
application.yml
application-dev.yml
application-test.yml
application-prod.yml
Activate the environment in the main configuration:
spring:
profiles:
active: dev
It can also be overridden through startup parameters:
java -jar app.jar --spring.profiles.active=prod
Single file multi-document approach

YAML can use --- to separate multiple documents and specify the corresponding environment through spring.config.activate.on-profile.
spring:
application:
name: demo
---
spring:
config:
activate:
on-profile: dev
server:
port: 8080
---
spring:
config:
activate:
on-profile: prod
server:
port: 80Development tools and hot deployments
After the introduction of DevTools, application restarts can be triggered when the classpath changes. It belongs to a development aid and should not be used as a deployment solution in a production environment.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
The IDE also needs to turn on automatic compilation or manually triggered builds, otherwise the modified class files will not be updated and DevTools will not restart the application.
Lombok simplified entity classes
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Boolean married;
private LocalDate birth;
private Map<String, String> maps;
private List<String> friends;
private Dog dog;
}Lombok generates common methods during the compilation phase. When using it, you should install an IDE plug-in and turn on annotation processing to avoid editor false positives.
Configure Spring MVC interceptors
Writing interceptors
Spring Boot 3 uses the Servlet API under the jakarta.servlet package.
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) {
System.out.println("preHandle");
return true;
}
@Override
public void postHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) {
System.out.println("postHandle");
}
}Register Interceptor
It is recommended to register the interceptor itself as a Bean and inject it into the configuration class through the constructor.
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
private final MyInterceptor myInterceptor;
public MyMvcConfig(MyInterceptor myInterceptor) {
this.myInterceptor = myInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/login", "/error");
}
}@Component
public class MyInterceptor implements HandlerInterceptor {
// 拦截逻辑
}
Integrate Druid data sources
When using the Druid Starter corresponding to Spring Boot 3, there is no need to reintroduce ordinary druid dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-3-starter</artifactId>
<version>1.2.23</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
url: jdbc:mysql://localhost:3306/java2601?serverTimezone=UTC&characterEncoding=utf8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
max-active: 10
min-idle: 3
initial-size: 2
max-wait: 10000test data source
@SpringBootTest
class SpringBootDemoApplicationTests {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
void testJdbcTemplate() {
List<Map<String, Object>> list =
jdbcTemplate.queryForList("SELECT * FROM t_user");
System.out.println(list);
System.out.println(jdbcTemplate.getDataSource());
}
}Database accounts and passwords should not be submitted to public warehouses. Real projects can provide sensitive configurations through environment variables, external configuration files, or key management services.
If you enjoyed this, leave a comment~