Spring云配置客户端属性未得到解决

时间:2016-09-14 03:12:18

标签: spring-boot spring-cloud spring-cloud-netflix spring-cloud-config

我对Spring Cloud和Spring外部配置的概念很陌生,实际上是昨天开始的。

我创建了一个配置服务器,从本地Git存储库中挑选配置,一个微服务也是配置客户端和一个Eureka驱动的服务发现服务器。

以下是我主要从互联网上的各种资源中借用的代码 -

Config Server - application.yml:

server:
  port: 8888

spring:
  cloud:
    config:
      server:
        git:
          uri: file:///${user.home}/config-repo

配置服务器 - 主类(引导程序)

@EnableConfigServer
@SpringBootApplication
public class CloudConfigServerApplication {

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

config-repo是我机器上的本地git repo,并且有一个带有配置客户端应用程序名称的.yml文件,即authmanager.yml

eureka:
    client:
        serviceUrl:
            defaultZone: http://127.0.0.1:8761/eureka/
        healthcheck:
            enabled: true
        lease:
            duration: 5
spring:
    application:
        data:   
            mongodb:
                host: localhost
                port: 27017
                database: edc_mc
logging:
    level:
        org.exampledriven.eureka.customer.shared.CustomerServiceFeignClient: FULL

现在运行配置服务器后,下面是结束点http://localhost:8888/authmanager/default -

的输出
{"name":"authmanager","profiles":["default"],"label":"master","version":"0ca6ca7b4502b9bb6ce1bf8efeb25516682cf79a","propertySources":[{"name":"file:///C:\\Users\\username/config-repo/authmanager.yml","source":{"eureka.client.serviceUrl.defaultZone":"http://127.0.0.1:8761/eureka/","eureka.client.healthcheck.enabled":true,"eureka.client.lease.duration":5,"spring.application.data.mongodb.host":"localhost","spring.application.data.mongodb.port":27017,"spring.application.data.mongodb.database":"db_name","logging.level.org.exampledriven.eureka.customer.shared.CustomerServiceFeignClient":"FULL"}}]}

微服务+配置客户端代码 -

bootstrap.yml -

server:
  port: 9097

spring:
  application:
    name: authmanager
  cloud:
    config:
      uri: http://localhost:8888

客户 - 主类(引导程序) -

@SpringBootApplication
@EnableDiscoveryClient
@EnableWebMvc
public class CloudLoginManagerApplication {

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

配置客户端中的控制器类,我想使用配置文件属性 -

@RefreshScope
@RestController
@RequestMapping("/auth")
public class MyController {

    @Value("${spring.application.data.mongodb.database}")
    String env_var;

为了清楚起见,请删除其余代码。

这是我得到的错误 -

Could not resolve placeholder 'spring.application.data.mongodb.database' in string value "${spring.application.data.mongodb.database}"

像server.port这样的其他属性不会产生问题。

我也尝试过Environment接口方式,但那也返回null。

请指点,我现在几乎已经死了。

谢谢,

AJ

1 个答案:

答案 0 :(得分:6)

要启用云配置,您必须将spring-cloud-starter-config添加到您的依赖项。您可以通过检查/ env(可能需要添加执行器)来查看哪些属性可用来验证。

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