复习 Java后端 - springboot 框架
学习内容: 笔记-spring Boot1. 介绍视频地址:黑马程序员springboot基础速成课_哔哩哔哩_bilibili
SpringBoot概述:
介绍:SpringBoot称为搭建程序的脚手架或者说是便捷搭建基于Spring的工程脚手架。
作用:最主要作用就是帮助开发人员快速的构建庞大spring项目
优势:尽可能的减少一切xml配置,做到开箱即用,迅速上手
特点:让开发人员关注业务而非配置。
为什么使用SpringBoot?
- 减少复杂配置
- ssm 混乱的依赖管理
- 使用 SpringBoot 创建Java应用,使用Java -jar启动它,因 springboot 内嵌了web服务器,所以可得到一个生产级别的web工程
springBoot特点:
- 内嵌web服务器,如 tomcat,jetty,不需要去部署 war 包。直接使用 java -jar 即可启动
- 提供固定的启动器依赖去简化组件配置:实现开箱即用。启动器 starter 其实是 Spring Boot 提供的一个jar包,通过自己设置参数(.properties或.yml的配置文件),即可快速使用。
- 自动配置 spring 和其他有需要的第三方依赖
- 提供了大型项目需要的特性:内嵌服务器,安全,指标,健康检测等
-
创建 maven 工程
-
添加依赖(启动器依赖,spring-boot-starter-web)
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.5.RELEASE com.itheima hiema-springboot 1.0-SNAPSHOT 1.8 org.springframework.boot spring-boot-starter-web -
创建启动类(SpringBoot工程的入口)
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } } -
创建Controller
@RestController public class HelloController { @GetMapping("hello") public String hello() { return "hello,Spring-Boot!"; } } -
测试 (运行启动类)
2.3 Java代码方式配置spring-boot-starter-web 默认的应用服务器端口是 8080
使用 @Value 获取文件配置项,并结合 @Bean 注册组件到 Spring
| 注解 | 含义 |
|---|---|
| @Configuration | 声明该类为配置类【代替 xml 文件】 |
| @Bean | 声明该方法的返回值注入Bean容器【代替了标签】 |
| @PropertySource | 指定外部属性文件 |
| @Value | 属性注入 |
举例:
需求:使用Java代码配置数据库连接池,并可以在处理器中注入并使用
步骤:
-
添加依赖
com.alibaba druid 1.1.6 -
创建数据库连接参数的配置文件:jdbc.properties
# c3p0 jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8 jdbc.username=root jdbc.password=2697572005 --- # Druid jdbc.driverClassName=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8 jdbc.username=root jdbc.password=2697572005
-
创建配置类
@Configuration @PropertySource("classpath:jdbc.properties") public class JdbcConfig { @Value("${driverClassName}") String driverClassName; @Value("${url}") String url; @Value("${username}") String username; @Value("${password}") String password; @Bean public DataSource dataSource() { DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driverClassName); druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); return druidDataSource; } } -
改造处理器类注入数据源并使用
@Autowired private DataSource dataSource;
目标:使用 @ConfigurationProperties 实现 SpringBoot 配置文件配置项 读取和应用
需求:@Value 每次只能读取一个配置项,且只能读取到基本变量中,不能将配置项一次读取到一个对象中。
实现:使用 SpringBoot 注解 @ConfigurationProperties,将 Springboot 的配置文件中的配置项(配置文件默认名称必须为application.properties 或 application.yml)读取到-》一个对象中
实现步骤:
-
创建配置类 JdbcProperties 类,在该类上添加 @ConfigurationProperties
如果出现 “Spring Boot Configuration Annotation Processor not found in classpath”
需要在 pom.xml 中引入依赖:
org.springframework.boot spring-boot-configuration-processor true @ConfigurationProperties(prefix = "jdbc") public class JdbcProperties { private String driverClassName; private String url; private String username; private String password; public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } -
将 Jdbc.properties 修改名称为 application.properties
-
将 JdbcProperties 对象注入到 JdbcConfig 类,在类上添加注解@EnableConfigurationProperties(xxx.class)
@Configuration @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfig { @Bean public DataSource dataSource(JdbcProperties jdbcProperties) { DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(jdbcProperties.getDriverClassName()); druidDataSource.setUrl(jdbcProperties.getUrl()); druidDataSource.setUsername(jdbcProperties.getUsername()); druidDataSource.setPassword(jdbcProperties.getPassword()); return druidDataSource; } }
如果一组属性只有一个Bean需要使用,我们无需将其注入到一个类中,而是直接把@ConfigurationProperties(prefix="jdbc") 声明在需要使用 @Bean 的方法上,然后SpringBoot会自动调用这个 Bean 的 set 方法,然后完成注入 [使用的前提是:该类必须有对应属性的 set 方法]
@Configuration
public class JdbcConfig {
@Bean
@ConfigurationProperties(prefix = "jdbc")
public DataSource dataSource() {
return new DruidDataSource();
}
}
2.6 多个 yml 文件配置
配置文件除了可以使用 application.properties 类型,也可以使用后缀名为 .yml 或者 .yaml 的类型。
什么是 yml 文件?
yaml 是一种简洁的非标记语言,yaml以数据为中心,使用空白缩进,分行组织数据的方式,从而使得表示更加简洁易读。yml 文件和 properties 文件除了展示形式不相同外,其他功能和作用都是一样的,在项目中的读物方式不需要改变。
yml 的特征:
- 树状层级结构展示配置项
- 配置项之间如果有关系,需要分行空两格
- 配置项如果有值,需要在: 之后空一格再写配置值
目标:将多个 yml 文件在 applicatioin.yml 文件中配置激活
分析:
-
在 springboot 中多个 yml 配置文件是被允许的,名称必须为 application-***.yml,并且这些配置文件必须在 application.yml 中激活之后才能使用
# 有 application-a.yml application-b.yml # 激活 spring: profies: # 指定配置文件名称 active: abc,def测试:
@RestController public class HelloController { @Autowired private DataSource dataSource; @Value("${a.url}") private String aurl; @Value("${b.url}") private String burl; @GetMapping("hello") public String hello() { System.out.println("dataSource"+dataSource+aurl+burl); return "hello,Spring-Boot!"; } } -
如果properties和yml配置文件同时存在,那么两个配置文件同时有效,如果存在同名配置项会以 properties 文件为主
分析:在 spring.factories 文件中定义了很多自动配置类,可以根据在pom.xml文件中添加的启动器依赖去自动配置组件,也就是根据 启动器依赖 实例化
如何修改组件的参数?
- 查询需要修改组件的 配置项流程图 ,然后去修改 application.yml 文件
目标:使用 lombok 的注解实现 pojo 类的简化
分析:之前编写实体类,需要编写 set/get 方法使得实体类臃肿。lombok就是解决此问题而生。lombok是一个插件工具包,提供了 @Data,@Getter,@Setter 等注解简化实体类中的构造方法。
原理:lombok在编译阶段会根据注解自动生成对应的方法.
-
@Data:自动提供getter、settter、hashCode、equals、toString等方法。
-
@Getter:自动提供getter方法
步骤:
-
安装 lombok 插件:File->setting->Plugins,installed之后重启 Idea
-
添加 lombok 对应的坐标到项目pom.xml
org.projectlombok lombok -
改造 pojo 类
@Data public class User { private Integer id; private String username; private String password; }
server: port: 802. 访问静态资源
默认的静态资源路径为:
- classpath:/META-INF/resources/
- classpath:/resources/
- classpath:/satitic/ [常用]
- classpatch:/public
只要将静态资源放到这些目录中的任何一个,SpringMvc就会帮助我们处理。
3. 配置mvc拦截器目标:在 springboot 项目中配置自定义SpringMvc 拦截器,又保持Spring Boot的一些默认MVC特征。
步骤:
-
编写拦截器类(实现 HandlerInterceptor 接口)
@Slf4j public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.debug("this.is MyInterceptor.preHandle!"); return true; // 放行 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { log.debug("this.is MyInterceptor.postHandle!"); } // 页面渲染之后执行 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { log.debug("this.is MyInterceptor.afterCompletion!"); } } -
编写配置类实现 WebMvcConfigurer ,并添加 @configuration 注解来实现自定义部分SpringMvc配置
@Configuration public class MvcConfig implements WebMvcConfigurer { // 添加拦截器到 spring MVC 拦截器链 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor()) // 拦截器 .addPathPatterns("/**") // 拦截所有请求,包括静态资源 .excludePathPatterns("/","/login","/css/*","/imgs/*"); // 放行哪些特殊请求 } }
目标:配置SpringBoot自带默认的 hikari 连接池和使用 @Transactional 注解进行事务配置
分析:
-
事务配置:
-
添加事务相关的启动器依赖,数据库驱动
org.springframework.boot spring-boot-starter-jdbc mysql mysql-connector-java 8.0.18 -
编写业务类 UserService 使用注解 @Transactional
@Service public class UserService { public User queryById(Long id) { return new User(); } @Transactional public void saveUser(User user) { System.out.println("save success!"); } }
-
-
hikari 配置:只需要在 application 配置文件中指定数据库相关参数
spring: # hikari datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8 username: root password: 2697572005
目标:配置 Mybatis 在 springBoot 工程中的整合包,设置 mybatis 的实体类别名,输出执行 SQL 语句配置项
分析:
-
添加启动器坐标
org.mybatis.spring.boot mybatis-spring-boot-starter 2.0.1 -
配置 Mybatis:实体类别名包,日志,映射文件等
mybatis: # 实体类别名包 type-aliases-package: com.itheima.pojo # 映射文件路径【若采用注解开发则可不用配置】 mapper-locations: classpath:mappers/*.xml configuration: # 日志配置 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl -
配置 MapperScan
如果mapper少的话,可以单独在每一个mapper接口上添加 @Mapper 注解。如果很多,就需要在启动引导类中使用 @MapperScan 注解
@SpringBootApplication // @MapperScan :扫描 mybatis 所有的业务 mapper 接口所在的包路径 @MapperScan("com.itheima.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
目标:配置通用Mapper组件到 SpringBoot 项目中并使用 Mapper 接口
分析:通用Mapper:可以实现自动拼接 SQL 语句,所有的 mapper 都不需要编写任何方法,不需要编写 SQL 语句,极大的提高了开发效率。
步骤:
-
引入启动器坐标
tk.mybatis mapper-spring-boot-starter 2.1.5 -
改造 UserMapper 继承 Mapper
public interface UserMapper extends Mapper
{ } -
配置MapperScan
@SpringBootApplication @MapperScan("com.itheima.mapper") // 通用Mapper的注解 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } } -
修改 User 实体类添加 jpa 注解
@Data @Table(name = "user") public class User { @Id // 主键回填 @KeySql(useGeneratedKeys = true) private Long id; // @Column("nickname") private String username; private String password; } -
改造 UserService 实现具体业务功能
@Service public class UserService { @Autowired private UserMapper userMapper; public User queryById(Long id) { return userMapper.selectByPrimaryKey(id); } @Transactional public void saveUser(User user) { userMapper.insertSelective(user);// 选择性新增:如果字段值为空,则不会出现在SQL中 System.out.println("save success!"); } } -
测试
@RestController @RequestMapping("user") public class HelloController { @Autowired private DataSource dataSource; @Autowired private UserService userService; @GetMapping("/{id}") public User queryById(@PathVariable int id) { return userService.queryById(id); } @PostMapping public String saveUser(User user) { System.out.println("user"+user.toString()); userService.saveUser(user); System.out.println("user+"+user.toString()); return "success!"; } }
目标:在 SpringBoot 项目中使用 Junit 进行单元测试
分析:
-
添加启动器依赖
org.springframework.boot spring-boot-starter-test -
编写测试类
@RunWith(SpringRunner.class) @SpringBootTest // springBoot 做测试时,务必加上 @SpringBootTest 注解 public class UserServiceTest { @Autowired private UserService userService; @Test public void queryById() { User user = userService.queryById(2); System.out.println("user"+user); } @Test public void saveUser() { User user = new User(); user.setUsername("lsi"); user.setPassword("123"); userService.saveUser(user); } }注意:springBoot 做测试时,务必加上 @SpringBootTest 注解
目标:在 SPringBoot 中使用 Junit 测试 RedisTemplate 的使用
分析:
-
添加启动器依赖
org.springframework.boot spring-boot-starter-data-redis -
配置 appliation.yml 中修改 redis 的连接参数(redis需要提前启动)
spring: redis: host: localhost port: 6379 -
编写测试类应用 RedisTemplate 操作 redis 中的 5 中数据类型(string/hash/list/set/sorted set)
@Runwith(SpringRunner.class) @SpringBootTest public class RedisTest { @Autowired private RedisTemplate redisTempalte; @Test public void test() { // String redisTemplate.opsForValue().set("str0","heima"); // 方式二:redisTemplate.boundValueOps("str").set("heima"); System.out.println("str ="+redisTemplate.opsForValue().get("str")); // hash redisTemplate.boundHashOps("h_key").put("name","heima"); redisTemplate.boundHashOps("h_key").pub("age",14); Set set = redisTemplate.boundHashOps("h_key").keys(); System.out.println("hash 散列的所有域:"+set); List list = redisTemplate.boundHashOps("h_key").values(); System.out.println("hash 散列的所有域值:"+list); // list redisTemplate.boundListOps("l_keys").leftPush("a"); redisTemplate.boundListOps("l_keys").leftPush("b"); redisTemplate.boundListOps("l_keys").leftPush("c"); List list = redisTemplate.boundListOps("l_keys").range(0,-1); System.out.println("list 列表中的所有元素:"+list); // set redisTemplate.boundSetOps("s_keys").add("a","b","c"); Set set = redisTemplate.boundSetOps("s_keys").members(); System.out.println("set 集合中的所有元素:"+set); // ordered set redisTemplate.boundZSetOps("z_key").add("a","30"); redisTemplate.boundZSetOps("z_key").add("b","20"); redisTemplate.boundZSetOps("z_key").add("c","10"); Set set = redisTemplate.boundZSetOps("z_key").range(0,-1); System.out.println("zset 集合中的所有元素:"+set); } }
目标:将 SpringBoot 项目使用 maven 执行达成 jar 包并进行测试
分析:
-
需要添加打包组件将项目中的资源、配置、依赖包打到一个 jar 包,可以使用maven 的 package
org.springframework.boot spring-boot-maven-plugin -
部署:java -jar 包名
-
使用 postman 进行测试
-
安装 JBLSpringBootAppGen
在应用 SpringBoot 时,使用该插件可以自动生成启动引导类 Application.java 和 application.yml 配置文件



