SpringBoot - 资源文件配置读取

时间:2023-03-10 02:25:59
SpringBoot - 资源文件配置读取

Examp1:读取核心配置文件信息application.properties的内容

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

1、application.properties中自定义参数

test.msg=Hello World SpringBoot 

2、在controller中读取

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

注意:在@Value的${}中包含的是核心配置文件中的键名。

方法二:使用Environment方式

@RestController
public class WebController {
@Autowired
private Environment env; @RequestMapping("/index2")
public String index2(){
return "方式二:"+env.getProperty("test.msg");
}
}

注意:这种方式是依赖注入Evnironment来完成,在创建的成员变量private Environment env上加上@Autowired注解即可完成依赖注入,然后使用env.getProperty("键名")即可读取出对应的值

Examp2:读取自定义配置文件信息

导入jar包:

<dependency>
  <groupId>org.springframwork.boot</groupId>
  <artifactId>Spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

1、创建自定义配置文件 Manager.properties

manager.name = "shabi"
manager.age = "27"

2、创建相关实体类

//加上注释@Component,可以直接在其他地方使用@Autowired来创建其实例对象
@Component
@ConfigurationProperties(prefix = "author",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;
}
}

注意:在@ConfigurationProperties注释中有两个属性:

   locations:指定配置文件的所在位置

   prefix:指定配置文件中键名称的前缀

   使用@Component是让该类能够在其他地方被依赖使用,即使用@Autowired注释来创建实例。

3、测试Controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
public class ConfigController {
@Autowired
private MyWebConfig conf; @RequestMapping("/test")
public @ResponseBody String test() {
return "Name:"+conf.getName()+"---"+"Age:"+conf.getAge();
}
}