zoukankan      html  css  js  c++  java
  • 二、SpringBoot读取配置的几种方式

    读取application文件:

      在application.yml或者properties文件中添加:

     info.address = USA
    
     info.company = Spring
    
     info.degree = high

    1.Value注解读取方式

    @Component
    public class test01{
       @Value("${info.address}")
      private String name; }

    2.@ConfigurationProperties注解读取方式

    @Component          //必须是容器中的组件,才能使用此种属性绑定方式
    @ConfigurationProperties(prefix="info")
    public class Test02{
      private String address;
      private String company;
      private String degree;
    }

    支持数据校验和复杂类型数据封装:

    @Component          //必须是容器中的组件,才能使用此种属性绑定方式
    @ConfigurationProperties(prefix="info")
    @Validated
    public class Test02{
      @Email //address必须是邮箱格式的   
    private String address;   private String company;   private String degree; }

    3.@PropertySource读取指定文件(不能读取yml文件)

    资源目录下建立config/db-config.properties:

    db.username = root
    db.password = 123456
    @Component
    @PropertySource(value = {"config/db-config.properties"})
    public class test03{
      @Value("${db.username}")
      private String username;
    }

    @ConfigurationProperties(prefix = "db")
    @PropertySource(value = {"config/db-config.properties"})
    public class test04{
      private String username;
      private String password;
    }

     4.ImportResource

      导入spring的配置文件,让配置文件里面的内容生效;springboot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别,想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上:@ImportResource(locations = {"classpath:beans.xml'})

  • 相关阅读:
    高级查询及分页总结
    SQL编程
    线程同步
    创建和启动线程
    错题集04
    错题集03
    错题集02
    错题集
    新闻发布系统
    九大内置对象
  • 原文地址:https://www.cnblogs.com/amazing-eight/p/12420514.html
Copyright © 2011-2022 走看看