SpringBoot 从入门到光头 第九章 自定义


SpringBoot 从入门到光头 —— 第九章 自定义


1. Profile 功能

为了方便多环境适配,SpringBoot 简化了 Profile 功能

1.1. application-profile 功能

  • 默认配置文件 application.yaml 任何时候都会加载
  • 指定环境配置文件 application-[environmrent].yaml
  • 指定激活环境
    • 配置文件激活
    • 命令行激活:java -jar xxx.jar --spring.profiles.active=prod -person.name=yourname
      • 修改配置文件的任意值,命令行优先
  • 默认配置与环境配置同时生效
  • 同名配置项,Profile 配置优先

示例代码:

application.yaml

person:
  name: gregPerlinLi

spring:
  profiles:
    active: prod  # Specifies the active environment. Both the default profile and the profile for the specified environment take effect

server:
  port: 8080

applicton-prof.yaml

person:
  name: gregPerlinLi-prod

server:
  port: 8000

application-test.yaml

person:
  name: gregPerlinLi-test

server:
  port: 8888

com.yourname.boot.controller.HelloController

/**
 * @author gregPerlinLi
 * @since 2021-11-23
 */
@RestController
public class HelloController {
    @Value("${person.name: DefaultName}")
    private String name;

    @GetMapping(value = "/")
    public String hello() {
        return "Hello " + name;
    }
}

1.2. @Profile 条件的装配功能

使用示例:

@Configuration(proxyBeanMethods = false)
@Profile("production")
public class ProductionConfiguration {

    // ...

}

示例代码:

com.yourname.boot.bean.Person

/**
 * @author gregPerlinLi
 * @since 2021-11-23
 */
public interface Person {
    /**
     * Get name
     * 
     * @return name
     */
    String getName();
    /**
     * Get age
     * 
     * @return age
     */
    Integer getAge();
}

com.yourname.boot.bean.Boss

/**
 * @author gregPerlinLi
 * @since 2021-11-23
 */
@Component
@Profile("prod")
@Data
@ConfigurationProperties("person")
public class Boss implements Person {
    private String name;
    private Integer age;
}

com.yourname.boot.bean.Staff

/**
 * @author gregPerlinLi
 * @since 2021-11-23
 */
@Component
@Profile("test")
@Data
@ConfigurationProperties("person")
public class Staff implements Person {
    private String name;
    private Integer age;
}

com.yourname.boot.controller.HelloController

/**
 * @author gregPerlinLi
 * @since 2021-11-23
 */
@RestController
public class HelloController {
    @Value("${person.name: DefaultName}")
    private String name;
    @Autowired
    private Person person;

    @GetMapping(value = "/")
    public String hello() {
        return person.getClass().toString();
    }
}

1.3. Profile 分组

使用示例:

spring:
    profiles:
        group:
            production:
                - proddb
                - prodmq

2. 外部化配置

https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config

  1. Default properties (specified by setting SpringApplication.setDefaultProperties)。
  2. @PropertySource annotations on your @Configuration classes. Please note that such property sources are not added to the Environment until the application context is being refreshed. This is too late to configure certain properties such as logging.* and spring.main.* which are read before refresh begins.
  3. Config data (such as application.properties files)
  4. A RandomValuePropertySource that has properties only in random.*.
  5. OS environment variables.
  6. Java System properties (System.getProperties()).
  7. JNDI attributes from java:comp/env.
  8. ServletContext init parameters.
  9. ServletConfig init parameters.
  10. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
  11. Command line arguments.
  12. properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
  13. @TestPropertySource annotations on your tests.
  14. Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.

2.1. 外部配置源

常用: Java属性文件、YAML文件、环境变量、命令行参数 …

2.2. 配置文件查找位置

  • classpath 根路径
  • classpath 根路径下 config 目录
  • Jar 包当前目录
  • Jar 包当前目录的 config 目录
  • /config 子目录的直接子目录

2.3. 配置文件的加载顺序

  1. 当前 Jar 包内部的 application.propertiesapplication.yaml
  2. 当前 Jar 包内部的 application-{profile}.propertiesapplication-{profile}.yaml
  3. 引用的外部 Jar 包的 application.propertiesapplication.yaml
  4. 引用的外部 Jar包的 application-{profile}.propertiesapplication-{profile}.yml

2.4. 总结

指定环境优先,外部优先,后面的可以覆盖前面的同名配置项

3. 自定义 starter

3.1. sterter 启动原理

  • starter-pom 引入 autoconfigurer

    StarterBoot

  • autoconfigurer 包中配置使用使用 META-INF/spring.factoriesEnableAutoConfiguration 的值,使得项目启动加载指定的自动配置类

  • 编写自动配置类 xxxAutoConfigurexxxProperties

    • @Configuration
    • @Conditional
    • EnableConfigurationProperties
    • @Bean

引入 starterxxxAutoConfiguration → 容器中放入组件 → 绑定 xxxProperties → 配置项

3.2. 自定义 starter

  • atguigu-hello-spring-boot-starter:启动器
  • atguigu-hello-spring-boot-starter-autoconfigure:自动配置包


文章作者: gregPerlinLi
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 gregPerlinLi !
  目录