Spring boot 读取配置文件信息

Spring boot 读取配置文件信息

1.使用@Value注解

这个注解必须必须写在Springboot管理的bean类中。

  • 配置文件

    server:
      port: 8090
      servlet:
        context-path: /demo
    
    demo:
      name: 亚瑟.摩根
      sex: man
      hehe: 呵呵
      school:
        small: 小学
        big: 大学
    
  • 	@Value("${demo.name}")
        private String name;
    
    	@Value("${demo.school.small}")
        private String small;
    
    

2.使用@ConfigurationProperties和@PropertySource注解

这个可以指定配置文件

  • 实体类

    @Component
    /**
     * 指定配置文件
     */
    @PropertySource(value = "application.yml")
    /**
     * 指定前缀
     */
    @ConfigurationProperties(prefix = "demo")
    public class ConfigBeanProp {
        private String name;
        private String sex;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    }
    
  • 使用类

    @Autowired
        private ConfigBeanProp configBeanProp;
    
世间种种的诱惑,不惊不扰我清梦
原文地址:https://www.cnblogs.com/javalisong/p/14097251.html