SpringBoot:读取核心配置文件application和自定义properties配置文件的方式

前言:
    SpringBoot的核心配置文件为application.properties,当然也可以自定义配置文件**.properties。

一.读取核心配置文件信息application.properties的内容
    核心配置文件是指在resources根目录下的application.properties或application.yml配置文件,读取这两个配置文件的方法有两种,如下:
    核心配置文件application.properties内容如下:

test.nessage=Hello World SpringBoot!

(1)方式一:使用@Value方式(常用)

@RestController  
public class WebController {  
    @Value("${test.message}")  
    private String msg;  
      
    @RequestMapping("/index1")   
    public String index1(){  
        return "方式一--使用@Value方式: "+msg;  
    }  
}

注意:在@Value的${}中包含的是核心配置文件中的键名。
访问:http://localhost:8088/index1时得到:“方式一–使用@Value方式:Hello World SpringBoot!”

(2)方式二:使用Environment方式

@RestController  
public class WebController {  
    @Autowired  
    private Environment environment;  
      
    @RequestMapping("/index2")   
    public String index2(){  
        return "方式二--使用Environment方式:"+environment.getProperty("test.message");  
    }  
}  

注意:这种方式是依赖注入Evnironment来完成,在创建的成员变量private Environment env上加上@Autowired注解即可完成依赖注入,然后使用env.getProperty(“键名”)即可读取出对应的值。
访问:http://localhost:8088/index2时得到:“方式二–使用Environment方式:Hello World SpringBoot!”

二.读取自定义配置文件信息,例如:author.properties
    为了不破坏核心文件的原生态,但又需要有自定义的配置信息存在,一般情况下会选择自定义配置文件来放这些自定义信息,这里在resources目录下创建配置文件author.properties

auth.name=Solin  
auth.age=22 

创建管理配置的实体类:

@Component  
@ConfigurationProperties(prefix = "auth",locations = "classpath:/author.properties") 
public class MyWebConfig{  
    private String name;  
    private int age;  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public int getAge() {  
        return age;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
}  

注意:
    1.在启动类上增加@EnableConfigurationProperties注解,激活自定义的配置类(重要)。
    2.使用@Component是让该类能够在其他地方被依赖使用,即可以直接在其他地方使用@Autowired注释来创建实例。
    3…在@ConfigurationProperties注释中有两个属性:
        locations:指定配置文件的所在位置
        prefix:指定配置文件中键名称的前缀
    springboot1.5之前的版本这么用,1.5版本之后取消了locations属性,使用@PropertySource注解代替“locations”属性。

@ConfigurationProperties(prefix ="auth") 
@PropertySource("classpath:/author.properties")

创建测试Controller:

@Controller    
public class ConfigController {  
    @Autowired  
    private MyWebConfig conf;  
      
    @RequestMapping("/test")   
    public @ResponseBody String test() {  
        return "Name:"+conf.getName()+"---"+"Age:"+conf.getAge();   
    }  
}  

访问:http://localhost:8088/test时得到:“Name:Solin---Age:22”


原作地址:https://blog.csdn.net/qq_23167527/article/details/77977326

猜你喜欢

转载自blog.csdn.net/qq_29229567/article/details/83618246