什么是Spring Boot
是一个基于spring级别的应用程序生产框架,简化了spring繁琐xml,采用springboot注解开发,自动装配组件,整合了各大框架,提高开发效率。
Spring Boot核心概念有哪些
1.自动配置 springboot 自动配置是核心的一块部分 ,根据项目中自动添加spring配置框架或者整合其他框架,不需要开发人员大量的配置代码。
2. 起步依赖 是预定义的一组依赖,可以帮助快速启动项目并减少Maven配置的复杂性 比如 mybatis-spring-boot-starter。
3.内置了tomcat,可以打包独立运行,不需要配置到外部应用服务器上。
4.Actuator:深入SpringBoot应用程序,看到SpringBoot内部信息 健康状态 核审日志。
5. 命令行界面 Spring Boot CLI提供了一个命令行工具 允许开发者通过命令快速创建Spring Boot应用并运行Groovy脚本 进一步加速了开发流程
SpringBoot 的作用是
1.简化开发,提高开发效率,无需写复杂xml配置文件,约定于配置的原则
2.支持重启于热部署 ,易于测试单元测试和集成测试。
Springboot常用注解
-
@SpringBootApplication:
-
这是 Spring Boot 应用的核心注解,包含了
@SpringBootConfiguration
、@EnableAutoConfiguration
和@ComponentScan
springboot配置注解,启动配置类注解,组件的包扫描。 -
@SpringBootConfiguration
:标记该类为配置类,相当于 XML 配置文件。 -
@EnableAutoConfiguration
:启用自动配置,Spring Boot 会根据项目中的依赖自动配置 beans。 -
@ComponentScan
:扫描并加载当前包及其子包下的所有组件 标记在业务层实现类上@Service 标记持久层接口上@Repository、标记在控制层类上@Controller、@Component 将此组件交给spring ioc容器进行管理 。
-
-
@RestController:
-
用于标记控制器类,相当于 @Controller + @ResponseBody 的组合,表明该类中的方法直接返回对象,由 Spring MVC 自动转换成 JSON 或 XML 形式响应给客户端。
-
-
@RequestMapping / @GetMapping / @PostMapping / @PutMapping / @DeleteMapping:
-
这些注解用于映射 HTTP 请求到 MVC 控制器的处理方法上。
-
@RequestMapping
是最基础的,可以处理任意类型的 HTTP 请求;其余的是它的具体化,分别对应 GET查询用的多、POST、PUT、DELETE 方法。
-
-
@Autowired:
-
用于自动装配 Bean。Spring 会自动将匹配的 Bean 注入到标记了此注解的字段或方法中。
-
-
@Value:
-
用来读取 properties 文件中的配置值,并将其注入到 Bean 中。
-
-
@ConfigurationProperties:
-
将一组相关的配置属性绑定到一个 Java 对象上,方便在代码中管理和使用这些配置。
-
-
@Profile:
-
用于指定组件应在哪些环境下生效。结合 Spring Profiles 功能,可以实现不同环境的配置切换。
-
-
@EnableXXX:
-
一系列开启功能的注解,如
@EnableWebMvc
、@EnableScheduling
、@EnableCaching
等,用于开启 Spring 的各种模块功能。
-
-
@Service、@Repository、@Component:
-
分别用于标记业务层、数据访问层和通用组件类,配合 @Autowired 使用,实现依赖注入。
-
-
@Entity:
-
JPA 注解,用于标记一个类为实体类,表示该类与数据库表相对应。
-
-
@Table:
-
JPA 注解,用于指定实体类对应的数据库表名以及表的元数据信息。
-
-
@Transactional:
-
标记在类或方法上,声明该类或方法的事务性。默认为读已提交,遇到运行时异常(未检查异常)时回滚事务。
-
Spring Boot 自动装配原理流程
图一
图2
1.创建项目springboot
添加父工程坐标
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.3</version>
</parent>
在pom添加springboot web启动依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
启动springboot类
package com.yunda;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDayoneApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDayoneApplication.class, args);
}
}
创建controller层
package com.yunda.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/save")
public String save(){
System.out.println("save...");
return "'user':'save'";
}
}
启动测试 内置了tomcat 端口为8080
Https访问接口
2.springboot 配置文件查看
配置文件有两种类型
1.application.porperties
2.application.yaml ,application.yml
配置文件必须放在加载的类目录下
属性配置文件的编写
spring.application.name=spring-boot-dayone
spring.jdbc.datasource.driverClassName=com.mysql.cj.jdbc.driver
spring.jdbc.datasource.url=jdbc:mysql:///springboot_01
spring.jdbc.datasource.username=root
spring.jdbc.datasource.password=root
读取配置文件 引入依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
package com.yunda.proper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Data
@Component
public class DataSourceProperties {
@Value("${spring.jdbc.datasource.driverClassName}")
private String driverClassName;
@Value("${spring.jdbc.datasource.url}")
private String url;
@Value("${spring.jdbc.datasource.username}")
private String username;
@Value("${spring.jdbc.datasource.password}")
private String password;
}
运行测试拿到以下结果
yaml配置文件写法
spring:
jdbc:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql:///springboot_data
username: root
password: root
批量注入属性
创建类添加属性和注解 @ConfigurationProperties(prefix = "spring.jdbc.datasource") 类读取属性配置
package com.yunda.proper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "spring.jdbc.datasource")
public class DataSourceProperties {
// @Value("${spring.jdbc.datasource.driverClassName}")
private String driverClassName;
// @Value("${spring.jdbc.datasource.url}")
private String url;
// @Value("${spring.jdbc.datasource.username}")
private String username;
// @Value("${spring.jdbc.datasource.password}")
private String password;
}
多环境使用
将项目分为 开发 生产 测试环境
创建三个配置文件
创建自定义启动工程
引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- Generated by https://start.springboot.io -->
<!-- 优质的 spring/boot/data/security/cloud 框架中文文档尽在 => https://springdoc.cn -->
<groupId>com.yunda</groupId>
<artifactId>spring-boot-daytow</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-daytow</name>
<description>spring-boot-daytow</description>
<properties>
<java.version>17</java.version>
</properties>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
创建实体业务类
package com.yunda.pojo;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "robot")
public class RobotProperties {
private String name;
private Integer age;
private String email;
}
创建业务层
package com.yunda.service;
import com.yunda.pojo.RobotProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PobotService {
@Autowired
private RobotProperties properties;
public String mode(){
System.out.println("姓名:"+properties.getName()+
"年龄"+properties.getAge()+
"邮箱"+properties.getEmail());
return "mode...";
}
}
package com.yunda.config;
import com.yunda.pojo.RobotProperties;
import com.yunda.service.PobotService;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({RobotProperties.class, PobotService.class})
public class RobotAutoConfiguration {
}
package com.yunda.config;
import com.yunda.pojo.RobotProperties;
import com.yunda.service.PobotService;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({RobotProperties.class, PobotService.class})
public class RobotAutoConfiguration {
}
使用自定义启动类
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>spring_boot_start</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
启动应用程序添加注解
@SpringBootApplication
@EnableRobot
public class SpringBootDaytowApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDaytowApplication.class, args);
}
}
使用工程添加配置文件
package com.yunda.controller;
import com.yunda.service.PobotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/Robot")
public class RobotController {
@Autowired
private PobotService pobotService;
@GetMapping("/money")
public String hello(){
System.out.println(pobotService.mode());
return "spring boot NB!";
}
}
启动测试 拿到数据
springboot整合mvc
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yunda</groupId>
<artifactId>spring-boot-day03</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-day03</name>
<description>spring-boot-day03</description>
<properties>
<java.version>17</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>3.0.5</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>17</source>
<target>17</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.yunda.SpringBootDay03Application</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
应用程序启动类
创建实体类
package com.yunda.pojo;
import lombok.Data;
@Data
public class User {
private String sex;
private Integer age;
private String password;
private String username;
}
controller层
package com.yunda.controller;
import com.yunda.pojo.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/getUser")
public User save(){
User user = new User();
user.setAge(19);
user.setSex("女");
user.setPassword("root");
user.setUsername("霉霉");
return user ;
}
}
访问测试
自定义拦截器
springboot方式实现
package com.yunda.interceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("MyInterceptor拦截器的preHandle方法执行....");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor拦截器的postHandle方法执行....");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("MyInterceptor拦截器的afterCompletion方法执行....");
}
}
实现WebMvcConfigurer 注册拦截器实现
package com.yunda.config;
import com.atguigu.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor ;
/**
* /** 拦截当前目录及子目录下的所有路径 /user/** /user/findAll /user/order/findAll
* /* 拦截当前目录下的以及子路径 /user/* /user/findAll
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
springboot整合mybatis
引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- Generated by https://start.springboot.io -->
<!-- 优质的 spring/boot/data/security/cloud 框架中文文档尽在 => https://springdoc.cn -->
<groupId>com.yunda</groupId>
<artifactId>spring-boot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-mybatis</name>
<description>spring-boot-mybatis</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
创建配置文件
spring.application.name=spring-boot-mybatis
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
#用来指定数据源类型
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
#指定mapper映射
mybatis.mapper-locations=classpath:/mapper/*.xml
启动应用程序
package com.yunda;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.yunda.mapper")
public class SpringBootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisApplication.class, args);
}
}
创建mapper数据层
package com.yunda.mapper;
import com.yunda.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("select id,username,address from user where id=#{id}")
public User getUser(Integer id);
}
创建pojo实体类
package com.yunda.pojo;
import lombok.Data;
@Data
public class User {
private Integer id;
private String username;
private String address ;
}
创建servie和实现业务类
创建controller层
package com.yunda.controller;
import com.yunda.pojo.User;
import com.yunda.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/queryBy/{id}")
public User queryById(@PathVariable Integer id){
User user = userService.getUser(id);
return user;
}
}
启动测试
打包项目在cmd执行