前言

springboot默认启动后会读取application.properties/application.yml配置文件的,因此在此配置文件中我们配置的属性可以通过@Value注解直接获取

在这里插入图片描述
在这里插入图片描述
那如果我们想自己配置一个配置文件时,该怎么获取文件值呢

一、通过ClassPathResource来获取

首先有一个自定义的配置文件 version.properties 在resources目录下
在这里插入图片描述
从配置文件中获取version值

private static Properties properties = new Properties();
ClassPathResource classpathResource = new ClassPathResource("version.properties");//该路径是相对于src目录的,即classpath路径
try {
	InputStream fileInputStream = classpathResource.getInputStream();
	properties.load(fileInputStream);
} catch (IOException e) {
   e.printStackTrace();
}
String version = properties.getProperty("version");
二、通过@ConfigurationProperties和 @PropertySource注解获取

配置文件不变,因为@ConfigurationProperties注解必须要加一个prefix属性,所以我们给version加一个前缀
在这里插入图片描述
新建一个用于获取version的配置文件

@Component
@ConfigurationProperties(prefix = "my")
@PropertySource(value = "version.properties")
public class VersionProperties {
    
    private String version;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}

然后在我们需要的类中获取这个version

	@Resource
    private VersionProperties versionProperties;

    @RequestMapping(value = "/getVersion")
    @ApiOperation(value = "获取系统版本")
    public Result<?> getSysVersion(){
        String version = versionProperties.getVersion();
        return Result.OK(version);
    }

注意自定义配置类要加@Component注解,在实际获取的类中需要注入进来。

其他方法大佬们在补充

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐