springboot加载指定位置的指定类型配置文件

方案一:简单使用注解实现

// 该注解用于容器启动时加载指定路径的配置文件
@PropertySource(value = {"file:G:/redis.conf"})
@Component
public class FileConfig {
}

将该注解加载到spring的容器中,可以加载任意位置的配置文件

@Component
// 引入g盘下面的redis.conf
@PropertySource(value = {"file:G:/redis.conf"}) 
// 引入类路径下面的配置文件
@PropertySource(value = {"classpath:redis.conf"}) 
// 引入多个配置文件如下
@PropertySource({"file:G:/redis.conf","classpath:redis.conf"})

获取配置也很简单,使用@Value注解

@RestController
@RequestMapping
public class CarController {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private String port;
}

方案二:springboot项目启动时,会加载你的自定义配置文件,可以像application.properties那样去配置和使用配置项,推荐使用这种
1.添加新类

public class MyConfEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {

    // 自定义配置文件路径
    private static final String CONF_PATH = "/home/richmail/webconf/monitor.conf";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

        try (FileInputStream fileInputStream = new FileInputStream(CONF_PATH)){
            Properties properties = new Properties();
            properties.load(fileInputStream);
            //第一个参数自定义
            PropertiesPropertySource propertySource = new PropertiesPropertySource("monitorConf", properties);
            //addFirst:自定义配置文件会覆盖springboot自带配置文件内容,addLast则不会
            environment.getPropertySources().addFirst(propertySource);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    public int getOrder() {
        return 0;
    }
}

2.在类路径中添加META-INF/spring.factories文件,内容为:
org.springframework.boot.env.EnvironmentPostProcessor=
cn.richinfo.config.MyConfEnvironmentPostProcessor

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值