SringBoot读取配置文件的几种操作

SringBoot读取配置文件的几种操作

1.读取yml的内容

information:配置信息
my-email:
  name:123
  email:1234567@163.com
poetry:
  location:中国古诗博大精深
  content:
    - name: 第一句
      description:我歌月徘徊,我舞影零乱
    - name: 第二句
      description:今夜月明人尽望,不知秋思落谁家
    - name: 第三句
      description:文章千古事,得失寸心知
  1. 读取简单的配置信息

    使用@Value("${information}")可以直接读取简单的配置信息

    例:

    @Value("${information}")
    String information;
    
  2. 通过@ConfigurationProperties读取并与 bean 绑定

    PoetryProperties 类上加了 @Component 注解,我们可以像使用普通 bean 一样将其注入到类中使用。

    @component是spring中的一个注解,它的作用就是实现bean的注入

    @Component
    @ConfigurationProperties(prefix = "poetry")
    @Setter
    @Getter
    @ToString
    class PoetryProperties {
        private String location;
        private List<Content> Content;
    
        @Setter
        @Getter
        @ToString
        static class Content {
            String name;
            String description;
        }
    }
    

    现在就可以像使用普通bean一样注入到类里使用

    @SpringBootApplication
    public class ReadConfigPropertiesApplication implements InitializingBean {
    
        private final LibraryProperties library;
    
        public ReadConfigPropertiesApplication(PoetryProperties poetry) {
            this.poetry = poetry;
        }
        
        public static void main(String[] args) {
            SpringApplication.run(ReadConfigPropertiesApplication.class, args);
        }
        
        @Override
        public void afterPropertiesSet() {
            System.out.println(poetry.getLocation());
            System.out.println(poetry.getContent());
        }
    }
    

    控制台输出:

    中国古诗博大精深
    [PoetryProperties.Content(name=第一句,description=我歌月徘徊,我舞影零乱......)]
    
  3. 通过@ConfigurationProperties读取并校验

    先将application.yml的内容修改,很明显邮件格式不正确

    my-email:
      name:123
      email:1234567@
    

    ProfileProperties类没有加 @Component 注解。所以可以再ProfileProperties的地方使用@EnableConfigurationProperties注册我们的配置bean

    @EnableConfigurationProperties注解的作用是:让使用 @ConfigurationProperties 注解的类生效。

    如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component或者实现了@Component的其他注解,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。

    简单点说@EnableConfigurationProperties的功能类似于@Component。

    @Getter
    @Setter
    @ToString
    @ConfigurationProperties("my-email")
    @Validated
    public class ProfileProperties {
       @NotEmpty
       private String name;
    
       @Email
       @NotEmpty
       private String email;
    
    }
    

    具体使用的代码与上一个类似

    @SpringBootApplication
    @EnableConfigurationProperties(ProfileProperties.class)
    public class ReadConfigPropertiesApplication implements InitializingBean {
        private final ProfileProperties profileProperties;
    
        public ReadConfigPropertiesApplication(ProfileProperties profileProperties) {
            this.profileProperties = profileProperties;
        }
    
        public static void main(String[] args) {
            SpringApplication.run(ReadConfigPropertiesApplication.class, args);
        }
    
        @Override
        public void afterPropertiesSet() {
            System.out.println(profileProperties.toString());
        }
    }
    

    因为邮箱地址不正确,所以运行时就会报错

    Binding to target org.springframework.boot.context.properties.bind.BindException:.......
    

    当我们修改为正确的邮箱地址后就可以正常打印出读取到的信息

    ProfileProperties(name=123, email=1234567@163.com)
    

2.读取指定 properties 文件

  1. properties文件准备

    url:https://www.baidu.com/
    
  2. @PropertySource读取指定 properties 文件

    @Component
    @PropertySource("classpath:website.properties")
    @Getter
    @Setter
    class WebSite {
        @Value("${url}")
        private String url;
    }
    

    使用方法:

    @Autowired
    private WebSite webSite;
    System.out.println(webSite.getUrl());
    
  3. 基于ClassLoder读取配置文件

    注意:该方式只能读取类路径下的配置文件,有局限但是如果配置文件在类路径下比较方便。

    Properties properties = new Properties();
    // 使用ClassLoader加载properties配置文件生成对应的输入流
    InputStream in = PropertiesMain.class.getClassLoader().getResourceAsStream("config/website.properties");
    // 使用properties对象加载输入流
    properties.load(in);
    //获取key对应的value值
    properties.getProperty("url");
    
  4. 基于 InputStream 读取配置文件

    注意:该方式的优点在于可以读取任意路径下的配置文件

    Properties properties = new Properties();
    // 使用InPutStream流读取properties文件
    BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/webSite.properties"));
    properties.load(bufferedReader);
    // 获取key对应的value值
     properties.getProperty("url");
    
  5. 通过 java.util.ResourceBundle 类来读取

    通过 ResourceBundle.getBundle() 静态方法来获取(ResourceBundle是一个抽象类),这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可

    Properties properties = new Properties();
    properties.getProperty("url");
    //website为属性文件名,放在包com.test.config下,如果是放在src下,直接用config即可
    ResourceBundle resource = ResourceBundle.getBundle("com/test/config/website");
    String key = resource.getString("url"); 
    
posted @ 2023-06-06 10:14  叶晨烁  阅读(61)  评论(0)    收藏  举报