如何使用配置服务器外部化spring应用程序配置?

时间:2017-03-23 07:06:40

标签: spring spring-boot config

我编写了自己的配置服务器来集中配置管理并使用API​​公开应用程序配置。现在我想从spring和spring-boot应用程序中使用配置属性。但我无法找到正确的方法。我尝试将配置服务器客户端代码用于侦听应用程序上下文启动事件并从配置服务器读取配置。但我无法将此配置注入其他bean。

如何从配置服务器读取应用程序配置(使用rest客户端)并将此读取配置注入应用程序环境以进行进一步处理?

1 个答案:

答案 0 :(得分:0)

为配置和您的应用程序创建一个应用程序

DBCC CHECKIDENT ('<YourTable>', RESEED, 0);
GO
配置服务器中的

application.yml

@SpringBootApplication
@EnableConfigServer
public class ConfigApplication  {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(ConfigApplication.class, args);
    }
}

并在src / main / resources / shared和your-service.yml中创建共享文件夹,如下所示

spring:
  cloud:
    config:
      server:
        native:
          search-locations: classpath:/shared
  profiles:
     active: native


security:
  user:
    password: pass

server:
  port: 8888
配置服务器中的

maven pom.xml

spring:
    security:
        basic:
            enabled: false

server:
    port: 8083

在你的服务春季启动应用程序中添加/src/main/resources/bootstrap.yml

像这样

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <finalName>config</finalName>
                </configuration>
            </plugin>
        </plugins>
    </build>

并将此依赖项添加到您的服务

spring:
  application:
    name: your-service
  cloud:
    config:
      uri: http://localhost:8888
      fail-fast: true
      username: user
      password: pass

首先运行配置服务器,然后运行Spring启动服务