SpringBoot学习笔记

SpringBoot学习笔记

SpringBOOt概念

SpringBoot提供了一种快速使用Spring的方式,基于约定大于配置的思想,让开发人员专注于逻辑业务,从而提高开发效率

SpringBoot功能

  1. 自动配置
    SpringBoot自动配置是一个运行时(应用启动时)的过程,自动决定Spring配置应该用哪个。
  2. 起步依赖
    起步依赖本质上是一个maven项目对象模型(Project Object Model, POM),定义了对其他库的传递依赖,将具备某种功能的坐标打包到一起,并提供一些默认的功能
  3. 辅助功能
    提供了一些大型项目中常见的非功能特性,如嵌入式服务器、安全、指标、健康检测、外部配置等
    SpringBoot并不是对Spring功能上的增强,而是提供一种快速使用Spring的方式

SpringBoot快速入门

需求

搭建SpringBoot工程,定义HelloChontroller.hello()方法,返回“Hello SpringBoot”

步骤

  1. 创建Meaven项目
  2. 导入SpringBoot起步依赖
  3. 定义Controller
  4. 编写引导类
  5. 启动测试

小节

  • SpringBoot在创建项目时,使用jar打包
  • SpringBoot的引导类是整个项目的入口,运行main方法即可启动
  • 使用SpringBoot和Spring构建的项目,业务代码方式完全一样

SpringBoot配置

配置文件分类

SpringBoot是基于约定的,很多配置有默认值,可以使用application.properties和application.yaml(yml)进行自定义配置

  • properties:
server.port=8080
  • yml:
server:
  port: 8080

小节

  • SpringBoot提供了2种配置文件类型:properties和yml/yaml
  • 配置文件名称必须是application
  • 在同一级目录下的优先级顺序:properties>yml>yaml

yaml

yaml是一种能够直观的被电脑识别的数据序列化格式,并且更容易被人类阅读,其文件的扩展名可以使用.yml或者.yaml

  • yaml格式
server:
  port: 8080
  address: 127.0.0.1

简洁,以数据为核心

yaml基本语法

  • 大小写敏感
  • 数据值前必须含有空格作为分隔符
  • 使用缩进表示层级关系
  • 缩进不允许使用Tab键,只允许使用空格
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • #表示注释

yaml数据格式

  • 对象(map):键值对的集合
person:
  name: zhangsan
#行内写法
person: {name: zhangsan}
  • 数组
address:
  - beijing
  - shanghai
# 行内写法
address: [beijing,shanghai]
  • 纯量:单个值,不可再分
msg1: 'hello \n world' # 单引号忽略转义字符
msg2: "hello \n world" # 双引号识别转义字符

yaml参数引用

name: zhangsan
person:
  name: ${name}

读取配置内容

  • @value
    @Value("${name}")
    private String name;
  • Enviroment
    @Autowired
    private Environment environment;
    System.out.println(environment.getProperty("person.name"));
  • @ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "person")
public class Person{}

profile

SpringBoot开发的应用通常会被安装到不同的环境(开发、测试、生产),其中数据库地址、服务器端口等等配置需要在打包时进行修改。profile能够对配置环境进行动态切换。

profile配置方式

  • 多profile文件方式(创建多个profile文件如application-dev.properties/application-pro.properties/application-test.properties)
  • yml多文档方式(利用---将文档分割)
---
server:
  port: 8083

spring:
  config:
    activate:
      on-profile: test
---

profile激活方式

  • 配置文件
spring:
  profiles:
    active: dev #dev/pro/test
  • 虚拟机参数:-Dspring.profiles.active=test
  • 命令行参数:--spring.profiles.active=pro

内部配置加载顺序

SpringBoot程序启动时,会从以下为主加载配置文件:

  1. file:./config/: 当前目录下的/config目录下
  2. file:./: 当前项目的根目录
  3. classpath:/config/: classpath的/config目录
  4. classpa:/: classpath的根目录
    加载顺序为上文的排列熟悉怒,高优先级配置的属性会生效

外部配置加载顺序

SpringBoot整合其他框架

整合Junit

  1. 引入start-test依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  1. 添加测试注解
  • @RunWith(SpringRunner.class)
  • @SpringBootTest(classes=启动类.class)
@SpringBootTest(classes = SpringBootStudyApplication.class)
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void test(){
        userService.add();
    }
}

整合redis

  1. 引入redis起步依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
  1. 配置redis属性
spring:
  redis:
    host:127.0.0.1
    port:6379
  1. 注入RedisTemplate模板
@Autowired
private RedisTemplate redistemplate;

整合mybatis

  1. 引入mybatis起步依赖,添加mysql驱动
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
  1. 编写DataSource和MyBatis相关配置
# datasource
spring:
  datasource:
    url: jdbc:mysql:///test_db
    username: root
    password:
    driver-class-name: com.mysql.cj.jdbc.Driver

# mybatis
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.rsk.springboot1.entity
  1. 注解开发
@Mapper
public interface UserMapper {

    public List<User> findAll();

}


@Autowired
private UserMapper userMapper;

SpringBoot原理分析

自动配置机制

Condition

Condition是Spring4.0增加的条件判断功能,可实现选择性的Bean创建,可自定义扩展

  • 自定义扩展步骤:
  1. 实现Condition接口(MyCondition.class)
public class MyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(ConditionOnClass.class.getName());
        //获取注解传入的元数据中的键值对map
        String[] value = (String[]) annotationAttributes.get("value");
        //自定义条件判断函数
        if (value[0].equals("0")){
            return true;
        }
        return false;
    }
}
  1. 自定义注解(ConditionOnClass)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(MyCondition.class)
public @interface ConditionOnClass {
    String[] value();
}

  1. Spring配置类中调用注解(UserConfig.class)
@Configuration
public class UserConfig {

    @Bean
    @ConditionOnClass(value = "1")
    public User user(){
        return new User();
    }
}

  • SpringBoot提供的常用条件注解:
  1. ConditionOnProperty:判断配置文件是否有对应属性和值后才初始化Bean
  2. ConditionOnClass:判断环境中是否有对应字节码文件才初始化Bean
  3. ConditionOnMissingBean:判断环境中没有对应的Bean才初始化Bean

@Enable*注解

@Enable*注解用于动态启动某些功能,底层原理是使用@Import注解导入一些配置类,实现Bean的动态加载

@Import注解

@Enable*底层依赖@Import注解导入所需要的类,使用@Import注解导入的类会被Spring容器加载到IOC容器中,以下有4种用法:

  • 导入Bean
  • 导入配置类
  • 导入ImportSelector实现类,一般用于加载配置文件中的类
  • 导入ImportBeanDefinitionRegistrar实现类

@EnableAutoConfiguration注解

  • @EnableAutoConfiguration注解内部使用@Import({AutoConfigurationImportSelector.class})来加载配置类
  • 配置文件位置:\META-INF\spring.factories,该配置文件中定义了大量的配置类,当SpringBoot启动时会自动加载这些配置类,初始化Bean
  • 不是所有Bean都会被初始化,在配置类中使用@Configuration注解来加载满足条件的Bean

自定义starter

需求:(自定义redis-starter,要求导入该坐标时,SpringBoot能够自动创建Bean)
步骤:

  1. 创建redis-spring-boot-autoconfigure模块
  2. 创建redis-spring-boot-starter模块,依赖前者
  3. 在redis-spring-boot-autoconfigure中初始化Jedis的Bean,并定义META-INF/spring.factories文件
  4. 在测试模块中引入自定义的redis-starter依赖,测试获取Jedis的Bean,操作redis

监听机制

启动流程分析

posted @   小小的脑袋  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
点击右上角即可分享
微信分享提示