Spring Boot

The first Spring Boot application
The target is to be returned by the server when the browser accesses the specified address Hello World。
Create projects and introduce dependencies
Projects can be created 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";
}
}Access after starting the project 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 packageAfter the construction is successful, you can use the target Catalog to find the JAR file.
run the project
java -jar target/项目名称.jarThe 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 It is a Web scene 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>Start 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() The Spring container is launched, automatic configuration is performed, and the embedded server is launched in the Web project.
@SpringBootApplication
@SpringBootApplication Is a combination annotation, which mainly includes the following capabilities:
@SpringBootConfiguration: Indicates that the current class is a Spring Boot configuration class and essentially has@Configurationrole.@EnableAutoConfiguration: Automatic configuration based on dependencies, existing beans, and configuration properties 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 will configure Spring MVC applications DispatcherServlet, request mapping, message converter and other components. When a developer declares a Bean of the same type himself, some automatic configurations will be subject to conditions.
profile
Spring Boot default support application.properties and application.yml。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: 2use @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 Suitable for batch binding of configurations under the same prefix. Property names support loose binding, such as the last-name Can be bound to Java properties lastName。
For configuration classes, you can also cooperate @ConfigurationPropertiesScan or @EnableConfigurationProperties Register without having to add it on the configuration object @Component。
@Value、@PropertySource with @ImportResource
@ValueSuitable for reading a small number of independent configurations.@PropertySourceAdditional.propertiesFile, but does not directly support YAML.@ImportResourceTraditional Spring XML configurations can be imported.
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.ymlActivate the environment in the main configuration:
spring:
profiles:
active: devIt can also be overridden through startup parameters:
java -jar app.jar --spring.profiles.active=prodSingle file multi-document approach

YAML can be used --- Separate multiple documents and pass spring.config.activate.on-profile Specify the corresponding environment.
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
Use of Spring Boot 3 jakarta.servlet The Servlet API under the 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, you don’t need to introduce ordinary people repeatedly. druid Dependence.
<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~