spring boot启动无法获取spring.application.name问题,bootstrap.yml配置获取不到的问题,spring.cloud.bootstrap.enabled参数

这个适合新版本的springcloud,且整个配置获取不到的问题,如果着急看结果的朋友,划到最后

今天在体验spring-cloud的时候,发现一个问题,就是com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository报了spring.application.name找不到,

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.application.name' in value "${spring.application.name}"
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1415) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:608) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.3.jar:5.3.3]
	... 19 common frames omitted
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.application.name' in value "${spring.application.name}"
	at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178) ~[spring-core-5.3.3.jar:5.3.3]
	at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124) ~[spring-core-5.3.3.jar:5.3.3]
	at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core-5.3.3.jar:5.3.3]
	at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-5.3.3.jar:5.3.3]
	at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175) ~[spring-context-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:936) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1321) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.3.jar:5.3.3]
	... 31 common frames omitted

配置文件如下

之后排查原因,发现其实spring.profiles.active也没有获取到,那么初步判断整个文件都没有获取到,spring-boot在读取文件的时候,会使用yaml的组件进行读取,之后排查该组件的读取内容,发现bootstrap没有读取到,只读取了application的文件

spring-boot有一个配置,是读取配置文件名的,叫做spring.config.name,这个配置决定spring-boot读取哪些配置名的文件,如果读取不到,默认读取application的文件

那么在这里初步排查为没有读取到这个配置,之后排查将bootstrap写入这个配置的地方,在一个叫做BootstrapApplicationListener的类中,有一个方法使用了,并且将其写入到ApplicationEnvironmentPreparedEvent的配置变量中,这里的配置变量,也就是之后springboot在注入@Value值会寻找配置key的地方

那么要解决的是,怎么将bootstrap加入到这里边

在springboot启动的时候会发布启动事件,BootstrapApplicationListener监听的ApplicationEnvironmentPreparedEvent事件发布之后,那么就会触发BootstrapApplicationListener的事件监听执行

这里的BootstrapApplicationListener会判断是否开启bootstrap配置,配置key叫spring.cloud.bootstrap.enabled,这里我用的是比较新版本的springcloud,这里的bootstrap配置是默认关闭的,所以会导致获取不到bootstrap的配置文件

到这里基本上就排查完毕了,那么要做的是,启动的时候将这个配置加上,我的做法是在main方法启动的时候,将这个配置设为true,这样默认就启动了

    public static void main(String[] args) {
        args = Arrays.copyOf(args, args.length + 1);
        args[args.length - 1] = "--spring.cloud.bootstrap.enabled=true";
        SpringApplication.run(OrderApplication.class,args);
    }

 

参考文章:Spring Cloud 2020.0.0 版本 bootstrap.yml 失效的原因與解決

  • 11
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
Table of Contents Title Page Copyright and Credits Mastering Spring Cloud Packt Upsell Why subscribe? PacktPub.com Contributors About the author About the reviewer Packt is searching for authors like you Preface Who this book is for What this book covers To get the most out of this book Download the example code files Conventions used Get in touch Reviews Introduction to Microservices The blessings of microservices Building microservices with Spring Framework Cloud-native development Learning the microservices architecture Understanding the need for service discovery Communication between services Failures and circuit breakers Summary Spring for Microservices Introducing Spring Boot Developing applications with Spring Boot Customizing configuration files Creating RESTful Web Services API Documentation Using Swagger 2 together with Spring Boot Testing API with Swagger UI Spring Boot Actuator features Application information Health information Metrics Developer tools Integrating application with database Building a sample application Running the application Summary Spring Cloud Overview Beginning with the basics Netflix OSS Service discovery with Eureka Routing with Zuul Load balancing with Ribbon Writing Java HTTP clients Latency and fault tolerance with Hystrix Configuration management with Archaius Discovery and distributed configuration An alternative – Consul Apache Zookeeper Miscellaneous projects Distributed tracing with Sleuth Messaging and integration Cloud platform support Other useful libraries Security Automated testing Cluster features Projects overview  Release trains Summary Service Discovery Running Eureka on the server side Enabling Eureka on the client side Deregistration on shutdown Using discovery client programmatically Advanced configuration settings Refreshing the registry Changing the instance identificator  Preferring the IP address Response cache Enabling secure communication between client and server Registering a secure service Eureka API Replication and high availability Architecture of the sample solution Building the example application Failover Zones Zones with a standalone server Building an example application Summary Distributed Configuration with Spring Cloud Config Introduction to HTTP API resources Native profile support Building a server-side application Building a client-side application Adding a Eureka Server Client-side bootstrap approaches Config Server discovery Repository backend types Filesystem backend Git backend Different protocols Using placeholders in URIs Building a server application Client-side configuration Multiple repositories Vault backend Getting started with Vault Integration with Spring Cloud Config Client-side configuration Additional features Fail on start and retry Secure client Reload configuration automatically Solution architecture Reload configuration with @RefreshScope Consuming events from a message broker Monitoring repository changes on a Config Server Simulating change events manually Testing locally with a GitLab instance  Summary Communication Between Microservices Different styles of communication  Synchronous communication with Spring Cloud Load balancing with Ribbon Enabling communication between microservices using the Ribbon client Static load balancing configuration Calling other services Using RestTemplate together with service discovery Building example application Using Feign client Support for different zones Enabling Feign for an application Building Feign interfaces Launching microservices Inheritance support Creating a client manually Client customization Summary Advanced Load Balancing and Circuit Breakers Load balancing rules The WeightedResponseTime rule Introducing Hoverfly for testing Testing the rule Customizing the Ribbon client The circuit breaker pattern with Hystrix Building an application with Hystrix Implementing Hystrix's commands Implementing fallback with cached data The tripping circuit breaker Monitoring latency and fault tolerance Exposing Hystrix's metrics stream Hystrix dashboard Building an application with the dashboard Monitoring metrics on the dashboard Aggregating Hystrix's streams with Turbine Enabling Turbine Enabling Turbine with streaming Failures and the circuit breaker pattern with Feign Retrying the connection with Ribbon Hystrix's support for Feign Summary Routing and Filtering with API Gateway Using Spring Cloud Netflix Zuul Building a gateway application Integration with service discovery Customizing route configuration Ignoring registered services Explicity set service name  Route definition with the Ribbon client Adding a prefix to the path Connection settings and timeouts Secure headers Management endpoints Providing Hystrix fallback Zuul filters Predefined filters Custom implementations Using Spring Cloud Gateway Enable Spring Cloud Gateway for a project Built-in predicates and filters Gateway for microservices Integration with service discovery Summary Distributed Logging and Tracing Best logging practices for microservices Logging with Spring Boot Centralizing logs with ELK Stack Setting up ELK Stack on the machine Integrating an application with ELK Stack Using LogstashTCPAppender Using AMQP appender and a message broker Spring Cloud Sleuth Integrating Sleuth with an application Searching events using Kibana Integrating Sleuth with Zipkin Running the Zipkin server Building the client application Analyze data with the Zipkin UI Integration via message broker Summary Additional Configuration and Discovery Features Using Spring Cloud Consul Running Consul agent Integration on the client side Service discovery Health check Zones Client settings customization Running in clustered mode Distributed configuration Managing properties in Consul Client customization Watching configuration changes Using Spring Cloud Zookeeper Running Zookeeper Service discovery Client implementation Zookeeper dependencies Distributed configuration Summary Message-Driven Microservices Learning about Spring Cloud Stream Building a messaging system Enabling Spring Cloud Stream Declaring and binding channels Customizing connectivity with the RabbitMQ broker Integration with other Spring Cloud projects The publish/subscribe model Running a sample system Scaling and grouping Running multiple instances Consumer groups Partitioning Configuration options Spring Cloud Stream properties Binding properties The consumer The producer The advanced programming model Producing messages Transformation Consuming messages conditionally Using Apache Kafka Running Kafka Customizing application settings Kafka Streams API support Configuration properties Multiple binders Summary Securing an API Enabling HTTPS for Spring Boot Secure discovery Registering a secure application Serving Eureka over HTTPS Keystore generation Configurating SSL for microservices and Eureka server Secure configuration server Encryption and decryption Configuring authentication for a client and a server Authorization with OAuth2 Introduction to OAuth2 Building an authorization server Client configuration Using the JDBC backend store Inter-service authorization Enabling SSO on the API gateway Summary Testing Java Microservices Testing strategies Testing Spring Boot applications Building the sample application Integration with the database Unit tests Component tests Running tests with an in-memory database Handling HTTP clients and service discovery Implementing sample tests Integration tests Categorizing tests Capturing HTTP traffic Contract tests Using Pact Consumer side Producer side Using Spring Cloud Contract Defining contracts and generating stubs Verifying a contract on the consumer side Scenarios Performance testing Gatling Enabling Gatling Defining the test scenario Running a test scenario Summary Docker Support Introducing Docker Installing Docker Commonly used Docker commands Running and stopping a container Listing and removing containers Pulling and pushing images Building an image Networking Creating a Docker image with microservices Dockerfiles Running containerized microservices Building an image using the Maven plugin Advanced Docker images Continuous Delivery Integrating Jenkins with Docker Building pipelines Working with Kubernetes Concepts and components Running Kubernetes locally via Minikube Deploying an application Maintaining a cluster Summary Spring Microservices on Cloud Platforms Pivotal Cloud Foundry Usage models Preparing the application Deploying the application Using CLI Binding to services Using the Maven plugin Maintenance Accessing deployment details Managing application life cycles Scaling Provisioning brokered services The Heroku platform Deployment methods Using the CLI Connecting to the GitHub repository Docker Container Registry Preparing an application Testing deployments Summary

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值