zoukankan      html  css  js  c++  java
  • Spring Boot 自定义参数

    2种取值方式区别是使用@Value注解的属性,必须在配置文件中存在,否则启动检查不通过,会报错导致无法启动。

    JAVA类

    1, 使用@Value注解方式

    @Component
    public class AliyunConfig {
        @Value("${oss.accessKeyId}")
        private String accessKeyId;
        @Value("${oss.accessKeySecret}")
        private String accessKeySecret;
    
        ...
    }
    

    2, 使用@ConfigurationProperties注解方式

    @ConfigurationProperties(prefix = "oss")
    public class AliyunConfig {
        
        private String accessKeyId;
        
        private String accessKeySecret;
    
        ...
    }
    

    配置文件

    application-dev.yml

    oss:
      accessKeyId: xxxxxx
      accessKeySecret: xxxxxxxxx
    

    @ConfigurationProperties 配置激活方式

    1, 增加@Component注解

    让 Component Scan 扫描到, 显然当类所在的包被 Spring @ComponentScan 注解扫描到才会生效

    2, 通过 Spring 的 Java Configuration 特性实现同样的效果

    @Configuration
    public class BeanConfig {
        @Bean
        public AliyunConfig aliyunConfig() {
    	return new AliyunConfig();
        }
    }
    

    3,使用 @EnableConfigurationProperties 注解

    让我们的类被 Spring Boot 所知道,在该注解中其实是用了@Import(EnableConfigurationPropertiesImportSelector.class) 实现

    @Configuration
    @EnableConfigurationProperties(AliyunConfig.class)
    public class BeanConfig {
    
    }
    

    @ConfigurationProperties 配置验证

    类使用 @Validated注解,在字段上添加 bean validation 注解

    @Data
    @ConfigurationProperties(prefix = "oss")
    @Validated
    public class AliyunConfig {
        
        @NotNull private String accessKeyId;
        
        private String accessKeySecret;
    
        ...
    }
    
  • 相关阅读:
    python基础-第十二篇-12.1jQuery基础与实例
    python基础-第十一篇-11.2DOM为文档操作
    [LC] 170. Two Sum III
    [Algo] 11. Rainbow Sort
    [LC] 31. Next Permutation
    [LC] 994. Rotting Oranges
    [LC] 863. All Nodes Distance K in Binary Tree
    [Algo] 132. Deep Copy Undirected Graph
    [LC] 138. Deep Copy Linked List With Random Pointer
    [Algo] 118. Array Deduplication IV
  • 原文地址:https://www.cnblogs.com/magicpose/p/11928552.html
Copyright © 2011-2022 走看看