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

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

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);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/737631.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存