解决SpringCloud项目引用SpringCloud Config配置文件无效问题

发布时间:2023-08-18 16:30

报错问题

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'xxxx' in value "${xxxx}"

 

解决办法

将项目配置文件下的Spring Cloud Config Client配置信息写在   bootstrap.yml或者bootstrap.properties  文件中(而不是application.yml或者application.properties)

因为 bootstrap.yml 的优先级大于 application.yml,项目启动后收优先加载bootstrap.yml配置文件

 

原因分析

Spring Cloud Config Server项目配置文件 application.yml 如下:

server:
  port: 9002
spring:
  application:
    name: config-server
  profiles:
    active: native
  cloud:
    config:
      server:
        native:
          search-locations: /opt/bip/config
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka/
  instance:
    preferIpAddress: true
    lease-expiration-duration-in-seconds: 30
    lease-renewal-interval-in-seconds: 30

Eureka Server项目配置文件 application.yml 如下:

server:
  port: 9000
spring:
  application:
    #通过查看注册中心查看有哪些模块注册进了这个注册中心
    name: eureka-server
eureka:
  instance:
    hostname: 127.0.0.1
  client:
    #是否向服务注册中心注册自己,默认为true
    register-with-eureka: false
    #是否检索服务
    fetch-registry: false
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

Eurka网页监控如下:

解决SpringCloud项目引用SpringCloud Config配置文件无效问题_第1张图片

启动没有任何问题

接下是配置Spring Boot(调用Cloud Config Server下的配置信息) 项目配置 application.yml 如下:

server:
  port: 9001

spring:
  application:
    #通过查看注册中心查看有哪些模块注册进了这个注册中心
    name: service-demo
  cloud:
    config:
      #获取配置的策略
      name: config
      profile: dev
      #获取配置文件的分支,默认是master。如果是是本地获取的话,则无用
      label: dev
      #开启配置信息发现
      discovery:
        enabled: true
        #指定配置中心的service-id,便于扩展为高可用配置集群
        serviceId: config-server

eureka:
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:9000/eureka/

Controller代码如下:

@RestController
@RequestMapping("/index")
public class IndexController {

    @Value("${pname}")
    public String pname;

    @RequestMapping("hello")
    public String hello(String name){
        return "Service1: hello " +name +":"+pname;
    }

}

启动报错如下:

2021-04-02 11:19:17.338  INFO 7327 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
2021-04-02 11:19:17.440  INFO 7327 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Connect Timeout Exception on Url - http://localhost:8888. Will be trying the next url if available
2021-04-02 11:19:17.441  WARN 7327 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/config/dev/dev": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)
2021-04-02 11:19:17.443  INFO 7327 --- [           main] c.c.stm.yunnanstm.YunnanStmApplication   : No active profile set, falling back to default profiles: default
2021-04-02 11:19:18.021  INFO 7327 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=01cf18c7-5215-3034-82de-1e65de9e0574
2021-04-02 11:19:18.296  INFO 7327 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 9001 (http)
2021-04-02 11:19:18.304  INFO 7327 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-04-02 11:19:18.304  INFO 7327 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.43]
2021-04-02 11:19:18.392  INFO 7327 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-04-02 11:19:18.392  INFO 7327 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 935 ms
2021-04-02 11:19:18.432  WARN 7327 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'indexController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'pname' in value "${pname}"
2021-04-02 11:19:18.433  INFO 7327 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2021-04-02 11:19:18.443  INFO 7327 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-04-02 11:19:18.458 ERROR 7327 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'indexController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'pname' in value "${pname}"
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405) ~[spring-beans-5.2.13.RELEASE.jar:5.2.13.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1425) ~[spring-beans-5.2.13.RELEASE.jar:5.2.13.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.2.13.RELEASE.jar:5.2.13.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.13.RELEASE.jar:5.2.13.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.13.RELEASE.jar:5.2.13.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.13.RELEASE.jar:5.2.13.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.13.RELEASE.jar:5.2.13.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.13.RELEASE.jar:5.2.13.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) ~[spring-beans-5.2.13.RELEASE.jar:5.2.13.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.13.RELEASE.jar:5.2.13.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.13.RELEASE.jar:5.2.13.RELEASE]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.9.RELEASE.jar:2.3.9.RELEASE]
Disconnected from the target VM, address: '127.0.0.1:53174', transport: 'socket'

分析情况及

系统默认去 http://localhost:8888 而不是我们在eureka中注册的 http://localhost:9002/ ,说明我们application.yml配置文件 没有生效 ,而是加载了cloud.config.client默认配置,

一顿思考以及查看文档后发现 org.springframework.cloud.config.client.ConfigClientProperties 类中有配置uri信息为 http://localhost:8888。

@ConfigurationProperties("spring.cloud.config")
public class ConfigClientProperties {
    public static final String PREFIX = "spring.cloud.config";
    public static final String TOKEN_HEADER = "X-Config-Token";
    public static final String STATE_HEADER = "X-Config-State";
    public static final String AUTHORIZATION = "authorization";
    private boolean enabled = true;
    private String profile = "default";
    @Value("${spring.application.name:application}")
    private String name;
    private String label;
    private String username;
    private String password;
    private String[] uri = new String[]{"http://localhost:8888"};
    private String mediaType = "application/vnd.spring-cloud.config-server.v2+json";
    private ConfigClientProperties.Discovery discovery = new ConfigClientProperties.Discovery();
    private TlsProperties tls = new TlsProperties();
    private boolean failFast = false;
    private String token;
    private int requestReadTimeout = 185000;
    private int requestConnectTimeout = 10000;
    private boolean sendState = true;
    private Map headers = new HashMap();

分析结果办法

将项目配置文件下的Spring Cloud Config Client配置信息写在   bootstrap.yml或者bootstrap.properties  文件中(而不是application.yml或者application.properties)

因为 bootstrap.yml 的优先级大于 application.yml,项目启动后收优先加载bootstrap.yml配置文件

 

 

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号