栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot项目创建自定义配置文件,在代码中读取

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot项目创建自定义配置文件,在代码中读取

step1: 创建自定义配置文件

注意:创建的位置一般为resource包下,格式为xxxx.setting,xxxx.xml,xxx.properties,xxx.yml格式

step2:读取配置文件中的信息
方式一,通过ClassPathResource来获取
  Properties properties = new Properties();
  ClassPathResource classpathResource = new ClassPathResource("config/c.yml");//该路径是相对于src目录的,即classpath路径
  try {
         InputStream fileInputStream = classpathResource.getInputStream();
         properties.load(fileInputStream);
      } catch (IOException e) {
            e.printStackTrace();
   }
        String version = properties.getProperty("name");


方式二, 通过@ConfigurationProperties和 @PropertySource注解获取

 step1 : 创建对应的实体类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Configuration
@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false)
@PropertySource("classpath:config/b.properties")
@Data
@Component
public class RemoteProperties {
    private String uploadFilesUrl;
    private String uploadPicUrl;
}

@Configuration 表明这是一个配置类
@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false) 该注解用于绑定属性。prefix用来选择属性的前缀,也就是在remote.properties文件中的“remote”,ignoreUnknownFields是用来告诉SpringBoot在有属性不能匹配到声明的域时抛出异常。
@PropertySource("classpath:config/remote.properties") 配置文件路径
@Data 这个是一个lombok注解,用于生成getter&setter方法,详情请查阅lombok相关资料
@Component 标识为Bean

  step2 : 在代码中使用配置文件对应的实体类

在想要使用配置文件的方法所在类上表上注解
@EnableConfigurationProperties(RemoteProperties.class)
并自动注入
@Autowired
RemoteProperties remoteProperties; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

@EnableConfigurationProperties(RemoteProperties.class)
@RestController
@Component
public class TestService{
    @Autowired
    RemoteProperties remoteProperties;

    public void test(){
        String str = remoteProperties.getUploadFilesUrl();
        System.out.println(str);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/837198.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号