SpringBoot 中配置加载的优雅写法

463 阅读2分钟

相关的注解

springboot

  • @Configuration:定义配置类。被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
  • @ConfigurationProperties:用于将同前缀的配置封装成实体类,需要设置prefix属性,与@EnableConfigurationProperties注解一起使用
  • @EnableConfigurationProperties:自动加载@ConfigurationProperties注解的配置类,需要定义对应类。
  • @ConditionalOnMissingBean:它是修饰bean的一个注解,主要实现的是,当你的bean被注册之后,如果而注册相同类型的bean,就不会成功,它会保证你的bean只有一个,即你的实例只有一个,当你注册多个相同的bean时,会出现异常,以此来告诉开发人员。
  • @ConditionalOnProperty:是用来作为条件,配置它所配置的类等是否生效。
    • prefix:配置前缀
    • name:后缀
    • havingValue:该值与prefix.name配置的值相同,则注入的Bean生效
    • matchIfMissing:如果没有配置 prefix.name=havingValue,默认是生效的;false默认没有配置不生效

lombok

  • @Getter/@Setter:自动产生 getter/setter
  • @ToString:自动重写 toString() 方法
  • @EqualsAndHashCode:自动生成 equals(Object other) 和 hashcode() 方法
  • @NoArgsConstructor : 生成一个没有参数的构造器
  • @AllArgsConstructor : 生成一个包含所有参数的构造器
  • @RequiredArgsConstructor : 生成一个包含 "特定参数" 的构造器,特定参数指的是那些有加上 final 修饰词的变量

InitializingBean接⼝ Spring初始化bean的时候,如果bean实现了InitializingBean接⼝,会⾃动调⽤afterPropertiesSet⽅法。

实例

定义实体类,用于接收配置:

@Data
@ConfigurationProperties(prefix = ObsProperties.PREFIX)
public class ObsProperties  {

    /**
     * 配置前缀
     */
    public static final String PREFIX = "obs";

    public ObsType type;

    /**
     * 是否启用 oss,默认为:true
     */
    private boolean enable = true;

    /**
     * 对象存储服务的URL,对应 obs.endpoint
     */
    private String endpoint;

    /**
     * 自定义域名
     */
    private String customDomain;

    /**
     * true path-style nginx 反向代理和S3默认支持 pathStyle {http://endpoint/bucketname} false
     * supports virtual-hosted-style 阿里云等需要配置为 virtual-hosted-style
     * 模式{http://bucketname.endpoint}
     */
    private Boolean pathStyleAccess = true;

    /**
     * 区域
     */
    private String region;

    /**
     * Access key就像用户ID,可以唯一标识你的账户
     */
    private String accessKey;

    /**
     * Secret key是你账户的密码
     */
    private String secretKey;

    /**
     * 默认的存储桶名称
     */
    private String bucketName="default";

    public enum ObsType {
        HW,MINIO;
    }
}

定义配置类,用于加载数据到指定Bean:

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({ ObsProperties.class })
public class ObsAutoConfiguration {
    /**
     * Obs操作模板
     * @return Obs操作模板
     */
    @Bean
    @ConditionalOnMissingBean(ObsService.class)
    @ConditionalOnProperty(prefix = ObsProperties.PREFIX, name = "enable", havingValue = "true", matchIfMissing = true)
    public ObjectStorageService ossTemplate(ObsProperties properties) {
        ObjectStorageService objectStorageService = null;
        switch (properties.getType()) {
            case HW:
                objectStorageService = new HWObsService(properties);
                break;
            case MINIO:
                objectStorageService =new MinioService(properties);
                break;
            default:
                break;
        }
        return objectStorageService;
    }
}

根据配置实例化:

public class HWObsService implements InitializingBean {

    public void afterPropertiesSet() throws Exception {
         this.client = new ObsClient(obsProperties.getAccessKey(), obsProperties.getSecretKey(), obsProperties.getEndpoint());
    }

}