首页 文章

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

提问于
浏览
4

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

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

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

配置服务器 - 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 回答

  • 5

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

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

相关问题