当前位置: 移动技术网 > IT编程>开发语言>Java > springcloud项目配置拓展从本地config目录加载

springcloud项目配置拓展从本地config目录加载

2019年08月27日  | 移动技术网IT编程  | 我要评论
本文受阿里开源的Nacos启发,应用启动后从Nacos服务加载配置到应用中,想着本地开发的时候加载配置能否从本地存储中加载,这样也能加快开发效率 首先 我们来看下SpringCloud项目应用Nacos服务的 配置如下 然后在Nacos控制台加配置 经过如上之后,这样应用就能从Nacos取配置。 问 ...

本文受阿里开源的nacos启发,应用启动后从nacos服务加载配置到应用中,想着本地开发的时候加载配置能否从本地存储中加载,这样也能加快开发效率

首先

我们来看下springcloud项目应用nacos服务的bootstrap.yaml配置如下

spring:
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yaml
      discovery:
        server-addr: 127.0.0.1:8848
  application:
    name: demo
  profiles:
    active: db,redis,rabbit,es,zk

然后在nacos控制台加配置

经过如上之后,这样应用就能从nacos取配置。

问题点

笔者认为这里开发的时候如果能从文件系统中加载配置替代nacos,能加快开发效率,也能心情舒畅的coding业务代码了。

解决思路

分析

经过分析启动配置spring.factories和配置类nacosconfigproperties

org.springframework.cloud.bootstrap.bootstrapconfiguration=\
org.springframework.cloud.alibaba.nacos.nacosconfigbootstrapconfiguration

找到nacosconfigbootstrapconfiguration 代码如下

@configuration
@conditionalonproperty(name = "spring.cloud.nacos.config.enabled", matchifmissing = true)
public class nacosconfigbootstrapconfiguration {

    @bean
    @conditionalonmissingbean
    public nacosconfigproperties nacosconfigproperties() {
        return new nacosconfigproperties();
    }

    @bean
    public nacospropertysourcelocator nacospropertysourcelocator(
            nacosconfigproperties nacosconfigproperties) {
        return new nacospropertysourcelocator(nacosconfigproperties);
    }

}

里面关键是nacospropertysourcelocator实现的接口propertysourcelocator

/**
 * strategy for locating (possibly remote) property sources for the environment.
 * implementations should not fail unless they intend to prevent the application from
 * starting.
 *
 * @author dave syer
 *
 */
public interface propertysourcelocator {

    /**
     * @param environment the current environment.
     * @return a propertysource, or null if there is none.
     * @throws illegalstateexception if there is a fail-fast condition.
     */
    propertysource<?> locate(environment environment);

}

到了这里就明白怎么做了。

具体请看我分享的git库https://github.com/lyg123/springcloudlocalcofigdemo

新的bootstarp.yaml配置如下

spring:
  cloud:
    nacos:
      config:
        enabled: false
        server-addr: 127.0.0.1:8848
        file-extension: yaml
      discovery:
        server-addr: 127.0.0.1:8848
  application:
    name: demo
  profiles:
    active: db,redis,rabbit,es,zk

这样应用启动配置能从本地文件系统加载或nacos服务加载

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网