SpringBoot学习

一、YAML相关配置文件使用

1.配置文件类型

  • properties:和以前一样
server.port=8080
  • yml/yaml:需要在键和值中间添加空格
server:
   port: 8080
  • 配置文件加载顺序:application.properties->application.yml->application.yaml

2.基本语法

  • 大小写敏感
  • 数据值前边必须有空格,作为分隔符
  • 使用空格缩进表示层级关系,相同缩进为同一级
  • 缩进不允许使用Tab键,只允许空格(idea会自动将table转换为空格)

3.数据格式

  • 对象
user:
	age: 17
#行内写法
user: {age: 17}
  • 数组:使用"-"表示每个数组元素
address:
	- beijing
	- shanghai
	- #行内写法
address: [beijing,shanghai]
  • 纯量:
msg1: 'hello \n world' #单引号原样输出转移字符
msg2: "hello \n world" #双引号换行输出转移字符
  • 参数引用
user:
	name: ${userName}

二、Profile使用

1) profile用来完成不同环境下,配置动态切换的功能
2) profile配置方式
  • 多profile文件方式:提供多个配置文件,每个代表一种环境
    • application-dev.properties/yml 开发环境
    • application-test.properties/yml 测试环境
    • application-prod.properties/yml 生产环境
  • yml多文档方式
    • 在yml钟使用 “- - -” 分隔不同配置环境
3) profile激活方式
  • 配置文件:在配置文件中配置 Spring.profiles.active=dev
  • 虚拟机参数:在VM options指定:-Dspring.profiles.active=dev
  • 命令行参数:java -jar xxx.jar --spring.profiles.active=dev
3) SpringBoot内部配置加载顺序
  • SpringBoot程序启动时,会从以下位置加载配置文件:
    • file:./config/ :当前项目下的/config目录下的配置
    • file./ :当前项目根目录下
    • classpath:/config/ :classpath的/config目录下
    • classpath:/ :classpath的根目录下
  • 加载顺序为上下文排序顺序,所有配置互补生效,有冲突高优先级会生效

三、SpringBoot自动配置

1) condition条件接口模仿解析
  • 通过自定义类实现condition接口的matches()方法得到想要的条件
public class ClassConditional implements Condition {

    /**
     *
     * @param context spring上下文,可以获取ioc容器等
     * @param metadata 获取注解元数据
     * @return 如果环境中有输入条件的值即返回true
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        boolean flag = true;
        Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(ConditionOnClass.class.getName());
        String[] value = (String[]) annotationAttributes.get("value");
        for (String s : value) {
            try {
                Class.forName(s);
            } catch (ClassNotFoundException e) {
                flag = false;
            }
        }
        return flag;
    }
}
  • 添加自定义注解
/**
 * 添加该注解的类会使用ClassConditional的条件
 * value值会传入ClassConditional,使用meteData接受
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ClassConditional.class)
public @interface ConditionOnClass {
    String[] value();
}
  • 在配置类上添加注解,并给定需要的条件class
@Configuration
public class UserConfig {

    @Bean
    @ConditionOnClass("redis.clients.jedis.Jedis") //自定义
    public User user() {
        return new User();
    }

    @Bean
    @ConditionalOnProperty(name = "user", havingValue = "zhangsan", matchIfMissing = true) //原注解
    public User user2() {
        return new User();
    }
}
2) 依赖引用自动配置原理
  • @SpringBootApplication注解中添加有组合注解@EnableAutoConfiguration
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
  • @EnableAutoConfiguration中使用@Import({AutoConfigurationImportSelector.class})导入AutoConfigurationImportSelector类
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
  • AutoConfigurationImportSelector会从META-INF/spring.factories中加载所有的需要自动配置的类
  protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        List<String> configurations = new ArrayList(SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader()));
        ImportCandidates.load(AutoConfiguration.class, this.getBeanClassLoader()).forEach(configurations::add);
        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories nor in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. If you are using a custom packaging, make sure that file is correct.");
        return configurations;
    }
3) 依赖引用自动配置模仿
  • 添加配置类,通过读取配置文件加载(不需要加载可以不用写)
@Configuration //配置类标识
@EnableConfigurationProperties(value = HelloProperties.class) //如无需要无需添加
public class HelloServiceAutoConfiguration {

    private HelloProperties helloProperties;

    //通过构造方法注入配置属性对象HelloProperties
    public HelloServiceAutoConfiguration(HelloProperties helloProperties) {
        this.helloProperties = helloProperties;
    }

    @Bean
    @ConditionalOnMissingBean //不存在这种bean才创建
    public HelloService helloService() {
        return new HelloService(helloProperties.getName(), helloProperties.getAddress());
    }
}
  • 在resources目录下添加META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.testStarter.config.HelloServiceAutoConfiguration

四、SpringBoot监控

1) SpringBoot监控概述
  • SpringBoot自带监控功能Actuator,可以帮助实现对程序内部运行情况监控,比如监控状态、Bean加载情况、日志信息等。
2) Actuator监控使用
  • 导入依赖
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
  • 访问http://localhost:8080/actuator
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值