springboot

161 阅读6分钟

Spring缺点

  • 添加一个框架或技术时,需要添加大量的的maven坐标
  • 添加一个框架或技术时,引入的多个坐标要考虑版本兼容问题,否则可能出现依赖冲突
  • 添加一个框架或技术时,需要添加大量的配置

SpringBoot

SpringBoot对Spring的缺点进行了改善和优化,基于约定优于配置的思想,提供了大量的默认配置和实现

版本锁定

  • 解决是maven依赖版本容易冲突的问题,集合了常用的并且测试过的所有版本

起步依赖 - 启动器

  • 解决了完成某一个功能要整合的jar包过多的问题,集合了常用的jar包

自动配置

  • 解决了整合框架或者技术的配置文件过多,集合了所有的约定的默认配置

内置Tomcat

  • 通过内置的tomcat,无需再用其他外置的Tomcat就直接可以运行javaEE程序

SpringBoot 快速入门

搭建环境

<!--设置父工程:自己的工程=继承=>spring-boot-starter-parent=继承=>spring-boot-dependencies-->
<!--spring-boot-starter-parent:指定了JDK版本、字符编码-->
<!--spring-boot-dependencies: 版本锁定:解决依赖版本兼容问题-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.12.RELEASE</version>
</parent>

<dependencies>
    <!--web环境起步依赖(启动器)-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

启动类

//要求其他类必须在该启动类的同级包 或者 子包下面,因为SpringBoot会扫描启动类所在包以及子包里面的组件(@Component)等注解

@SpringBootApplication
public class QuickApplication {

    public static void main(String[] args) {
        SpringApplication.run(QuickApplication.class,args);
    }
}

SpringBoot 配置文件

resources下创建文件:

  1. application.yaml
  2. application.yml
  3. application.properties

注意:SpringBoot启动时会依次加载:yaml、yml、properties文件,如果多个配置文件同时存在,后加载的会覆盖前面加载的内容。 源码解析读取默认配置文件 run()方法调用了环境准备的监听器:

  • run()方法执行,最终调用了SpringApplication.prepareEnvironment()方法,其中一步就是使用事件监听完成环境准备
  • 当应用启动(执行了run()),会执行该事件监听器的onApplicationEvent(ApplicationEvent event)
  • 调用 ConfigFileApplicationListener 的postProcessEnvironment()方法进行环境初始化配置 配置文件可以存放的位置:
private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/";

配置文件默认名称:

private static final String DEFAULT_NAMES = "application";

YAML

  1. 大小写敏感

  2. 使用缩进表示层级关系,缩进的空格数量不重要,关键是相同层级必须左对齐

  3. 参数名和参数值之间用冒号分隔

    1. 参数名可以是一到多个单词组成,一个单词表示一个层级
    2. 参数值不需要使用引号,参数值和冒号之间必须有空格 YAML数据格式:
#简单类型
name: hawk
age: 23
single: true

#对象类型
player:
  name: dover
  age: ${age}
  birthday: 1998/1/2
  single: ${single}

#集合类型
players:
  - hawk
  - dover
#集合类型行内写法
names: [hawk,dover]

读取配置文件

  • 方式一: Environment 此对象是Spring框架提供的,用来表示整个应用运行时的环境,可以读取配置文件中的属性值并逐个注入到Bean对象的对应属性中
@RestController
public class HelloController {

    @Autowired
    Environment environment;

    @GetMapping("/hello")
    public String hello(){
        String name = environment.getProperty("name");
        //第二个参数可以指定获取到的参数类型
        Integer age = environment.getProperty("age", Integer.class);
        Boolean single = Boolean.valueOf(environment.getProperty("single"));
        String player = environment.getProperty("player");
        Date birthday = environment.getProperty("player.birthday", Date.class);
        String name2 = environment.getProperty("names[1]");
        System.out.println(name);
        System.out.println(age);
        System.out.println(single);
        System.out.println(player);
        System.out.println(birthday);
        System.out.println(name2);
        return "Hello";
    }
}
  • 方式二: @Value 此注解是Spring框架提供的,用来读取配置文件中的属性值并逐个注入到Bean对象的对应属性中
@Value("${player.name}")
private String name;
@Value("${player.age}")
private Integer age;
@Value("${player.birthday}")
private Date birthday;
@Value("${player.single}")
private Boolean single;
  • 方式三: @Configuration 此注解是SpringBoot框架提供的,用来快速、方便地将配置文件中的自定义属性值批量注入到某个Bean对象的多个对应属性中
@Configuration //配置类注解
@ConfigurationProperties("player") //配置属性注解
@Data
public class PlayerConfig {
    private String name;
    private Integer age;
    private Date birthday;
    private Boolean single;
}

@Autowired
private PlayerConfig playerConfig;

@GetMapping("/config")
public void config(){
    System.out.println(playerConfig);
}

多环境开发配置

可以根据应用环境创建多份配置文件

  1. 文件名可以是 application-{profile}.yml/properties,{profile}是变量用于自定义配置文件名称使用profile来区分不同的应用环境
  2. 由主配置文件来控制读取那个子配置

image.png

#多环境配置
spring:
  profiles:
    active: test

加载自定义配置

@PropertySource注解来实现

@PropertySource可以用来加载指定的配置文件,默认它只能加载*.properties文件

第一步:自定义配置

eponine.name=爱潘妮
eponine.hobby=音乐剧,小神马
eponine.alive=false

第二步:通过配置类批量加载配置

@Configuration
@PropertySource("classpath:config/eponine.properties")
@ConfigurationProperties(prefix = "eponine")
@Data
public class EponineConfig {
    private String name;
    private List<String> hobby;
    private Boolean alive;
}

SpringBoot 整合其它框架

整合Junit

spring官方提供了junit起步依赖,在pom.xml当中导入即可

测试类要在启动类同级或者子包下

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MyTest {

    @Autowired
    private EponineConfig eponineConfig;

    @Test
    public void TestBoot(){
        System.out.println(eponineConfig);
    }
}

整合SpringMVC

访问静态资源

springboot启动时,加载org.springframework.boot.autoconfigure.web.ResourceProperties资源属性类

public class ResourceProperties {
    //定义了静态资源路径
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = 
		new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
}

我们习惯会把静态资源放在classpath:/static/ 目录下。

拦截器配置

第一步:自定义一个springMVC拦截器类,实现 HandlerInterceptor 接口,并加入到IOC容器

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器拦截了请求");
        return true;
    }
}

第二步:自定义一个springMVC的配置类,实现WebMvcConfigurer接口

@Configuration
public class SpringConfiguration implements WebMvcConfigurer {

    @Autowired
    MyInterceptor interceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册拦截器
        registry.addInterceptor(interceptor)
                //添加拦截路径
                .addPathPatterns("/**")
                //不拦截的路径
                .excludePathPatterns("/hello",
                        "/value",
                        "/cinfig/**")
                //不拦截的静态资源路径
                .excludePathPatterns("/**.html",
                        "/css/**",
                        "/js/**",
                        "/img/**");
    }
}

整合Mybatis

添加依赖

<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
<!--mybatis起步依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

mapper代理到ioc容器

方式一:使用 @Mapper

@Mapper
public interface UserMapper {
    User selectById(Long id);
    void save(User user);
    void deleteById(Long id);
    void updateById(Long id);
}

方式二: 启动类扫描mapper接口

@MapperScan扫描

@SpringBootApplication
@MapperScan("com.eponine.mapper")
public class QuickApplication {

    public static void main(String[] args) {
        SpringApplication.run(QuickApplication.class,args);
    }
}

Druid连接池

导入druid依赖

<!--druid连接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.3</version>
</dependency>

修改application.yml

spring:
  # 指定连接池
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: root
    #指定连接池类型
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      #初始化连接池的的连接数据量
      initial-size: 5
      #连接池最小连接数
      min-idle: 5
      #获取连接等待超时时间 (毫秒)
      max-wait: 6000
      #最大连接数
      max-active: 20

      # 检测连接是否有效。建议配置为true,不影响性能,并且保证安全性,默认false
      test-while-idle: true
      # 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 默认true
      test-on-borrow: false
      # 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。默认false
      test-on-return: false

整合日志框架

自定义日志输出

# 日志配置
logging:
  level:
    # mapper包下日志级别
    com.eponine.mapper: debug
    # controller包下日志级别
    com.eponine.controller: info
  file:
    # 日志文件路径及名称
    # 不指定文件路径,windows环境会在项目根目录下创建日志文件
    #               linux在安装的tomcat根目录的bin目录下
    name: #E://quick-start.log

@Slf4j注解

可以在类上面添加@Sl4j注解,然后使用log对象打印日志,idea首先需要安装Lombok插件