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

问题描述:

我写了自己的配置服务器来集中配置管理并使用API​​公开应用程序配置。现在我想从弹簧和弹簧引导应用程序中使用配置属性。但我无法找出正确的方法。我尝试将我的配置服务器客户端代码放置在监听应用程序上下文启动事件并从配置服务器读取配置。但我无法将此配置注入其他bean。如何使用配置服务器外部化spring应用程序配置?

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

创建一个应用程序,用于配置和您在配置服务器

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


security: 
    user: 
    password: pass 

server: 
    port: 8888 

应用

@SpringBootApplication 
@EnableConfigServer 
public class ConfigApplication { 

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

application.yml并创建SRC共享文件夹/主/资源/共享和您的服务。像这样的yml

spring: 
    security: 
     basic: 
      enabled: false 

server: 
    port: 8083 

配置服务器中的maven pom.xml

<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> 
在您的服务春季启动应用程序

添加/src/main/resources/bootstrap.yml

这样

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

,并添加这种依赖于您的服务

<dependency> 
    <groupId>org.springframework.cloud</groupId> 
    <artifactId>spring-cloud-starter-config</artifactId> 
</dependency> 

第一次运行配置服务器,然后您的弹簧启动服务

+0

嗨阿里,我没有使用spring-cloud-config服务器,但我有我自己的配置服务器和配置客户端。 – user34567

+0

为什么你不使用云配置?你想写一个项目,如云配置:D –

+0

有几个要求我需要编写我自己的配置服务,当然我不喜欢重新发明*,但是这使我更多地控制数据模型,代码和功能。 – user34567