SpringBoot入门
SpringBoot学习目标
- 说出SpringBoot的作用
- 应用SpringBoot Yaml配置文件
- 了解SpringBoot自动配置原理
- 使用SpringBoot整合SpringMVC
- 使用SpringBoot整合连接池
- 使用SpringBoot整合Mybatis
- 使用SpringBoot整合Redis
- 部署SpringBoot项目
SpringBoot概述:
SpringBoot是便捷搭建,基于Spring的脚手架
,帮助开发人员快速的构建庞大的Spring项目,并且尽可能减少XML配置
,做到开箱即用,让开发更关注于业务;
SpringBoot的特点:
1 创建独立的Spring应用;
2 直接嵌入应用服务器,不需要部署war包;
3 提供固定的启动器依赖去简化组件配置;
4 自动配置Spring和其它的第三方依赖;
5 提供了一些大型项目中常见的其它非功能性特性;
6 绝对没有代码生成,也无需XML配置;
SpringBoot入门:
实现的案例要求:可以在浏览器中访问:http://localhost:8080/hello输出一串字符串;
实现步骤:
- 创建工程;
- 添加依赖;
- 创建启动类;
- 创建处理器Controller;
- 测试;
在SpringBoot中利用注解@RestController来取代下面两个的合成,
把类里面所有的内容都当成字符输出;
@Controller
@ResponseBody
创建启动类:
/**
* SpringBoot都有一个启动引导类
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,
args);
}
}
在Maven中添加依赖:
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.3.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
<java.version>1.8</java.version>
</properties>
JAVA代码方式配置
- java方式配置主要靠一些java类,以及java注解
@Configuration 声明一个类位配置类,替代XML文件
@Bean 声明在方法上,将方法的返回值加入Bean容器,替代Bean标签
@Value 属性注入
@PropertySource 指定外部属性文件
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
@Value("${jdbc.url}")
String url;
@Value("${jdbc.username}")
String username;
@Value("${jdbc.password}")
String password;
@Value("${jdbc.DriveClassName}")
String DriverClassName;
@Bean
public DataSource dateSource(){
DruidDataSource dateSource = new DruidDataSource();
dateSource.setDriverClassName(DriverClassName);
dateSource.setUrl(url);
dateSource.setPassword(password);
dateSource.setUsername(username);
return dateSource;
}
}
SpringBoot注入方式
使用@ConfigurationProperties
实现SpringBoot配置文件配置项的读取和应用。该注解可以将SpringBoot中配置文件的配置项,读取到一个对象中去。必须为application.xml或者application.yml
/**ConfigurationProperties 从Application配置文件中读取配置项
* prefix 表示配置项的前缀;
* 配置项类中的类变量名必须要与前缀之后的配置项名称保持松散绑定(相同)
*/
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
private String url;
private String driverClassName;
private String username;
private String password;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
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;
}
}
@Configuration
//@PropertySource("classpath:application.properties")
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
@Bean
public DataSource dateSource(JdbcProperties jdbcProperties){
DruidDataSource dateSource = new DruidDataSource();
dateSource.setDriverClassName(jdbcProperties.getDriverClassName());
dateSource.setUrl(jdbcProperties.getUrl());
dateSource.setPassword(jdbcProperties.getPassword());
dateSource.setUsername(jdbcProperties.getUsername());
return dateSource;
}
}
ConfigurationProperties和Value之间的比较;
优势:松散绑定
更优雅的一种注入方式:
@Bean
//声明要注入的属性前缀,SpringBoot会自动把相关属性通过set方法注入到DateSource中
@ConfigurationProperties(prefix = "jdbc")
public DataSource dataSource(){
return new DruidDataSource();
}
- 使用ConfigurationProperties编写配置项类,将配置文件中的配置项设置到对象中;
- 使用ConfigurationProperties应用在方法上面;
多个yml文件配置
将application.xml替换为applicaiton.yml进行测试
yml文件的特征:
- 树层结构展示配置项
- 配置项之间如果有关系的化需要分行
- 配置项如果有值的话需要在: 后面空一格,再写配置项的值;
将application.properties配置文件修改为application.yml
jdbc:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot_test
username: root
password: root
多个yml配置文件再SpringBoot中是被允许的;这些配置文件的名称必须为application-***.yml,这些配置文件必须在application.yml配置文件中激活才能使用;
properties和yml文件同时存在SpringBoot中,那么这两类配置文件都有效;
如果有properties的配置项和yml的配置项冲突的话以applicaiton.xml为主。
SpringBoot的自动配置的原理
- 在META-INF\Spring.fatories文件中定义了很多的自动配置类,可以根据在pom.xml中添加的启动器依赖自动配置组件
- 通过如下流程可以修改application配置文件,改变自动配置的组件默认参数。
springboot自动配置原理
lombok的应用
使用lombok的注解实现pojo类的简化
使用SpringBoot整合SSM工程
lombok是一个插件工具类包,提供了注解@Data,@Getter等这些注解去简化实体类中的构造方法,get/set等方法的编写。
//在编译阶段会根据注解自动生成对应的方法,data包含get/set/hashcode/equals/toString等方法;
@Data
@Slf4j
public class User {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private Integer sex;
private Date birthday;
}
SpringBoot整合SpringMVC拦截器
- 修改tomcat
查询***properties,设置配置项(前缀+类变量名)到application配置文件中
server:
port: 80
- 访问项目中的静态资源;
查询静态资源文件的放置;放置静态资源并访问这些资源
classpath:/META-INF/resources
classpath:/resources
classpath:/static
classpath:public
整合SpringBoot中的拦截器
可以在项目中配置自定义SpringMVC拦截器
- 编写拦截器(HandlerInterceptor)
- 编写配置类实现(WebMvcConfigurer),在该类中添加各种组件;
- 测试
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.debug("这是MyInterceptor的preHandler方法");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.debug("这是MyInterceptor的postHandler方法");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.debug("这是MyInterceptor的afterCompletion方法");
}
}
@Configuration
public class MvcConfig implements WebMvcConfigurer {
//注册拦截器
@Bean
public MyInterceptor myInterceptor(){
return new MyInterceptor();
}
//添加拦截器到Spring mvc拦截器链
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor()).addPathPatterns("/*");
}
SpringBoot 事物配置
- 添加事物相关的启动器依赖 ,Mysql相关依赖
- 编写业务类UserService在里面使用事物注解@Transactional
数据库连接池hikari配置
只需要将application配置文件中指定数据库相关参数。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
spring:
profiles:
active: abc,def
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot_test
username: root
password: root
- 添加启动器依赖
- 配置Mybatis,实体类别名包,日志,映射文件等。
- 配置MapperScan
#1
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
#2
mybatis:
#实体类别名包路径
type-aliases-package: cn.lxy.pojo
#映射文件路径
mapper-locations: classpath:mappers/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#3
@SpringBootApplication
@MapperScan("cn.lxy.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
SpringBoot集成通用Mapper
- 添加依赖启动器
- 改造UserMapper继承Mapper
- 修改启动引导类中扫描注解
- 修改User实体类添加JPA注解
- 改造UserService实现