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

// 该注解用于容器启动时加载指定路径的配置文件
@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

Logo

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

更多推荐