Spring Cloud Config Server - Properties not being picked up - spring-boot

We are trying to add Spring Cloud Config Server to our project to externalize the configuration.
We have created a Config Server which connects to the Git repo and seems to be working correctly. However when we start a sample client it we get a message fetching config from server. Located environment but then a message to set a property which we have set in the corresponding yaml file in the git repo.
Config Server bootStrap.yml
spring:
application:
name: configuration-service
server:
port: 8888
Config Server application.yml
spring:
profiles:
active: dev
security:
user:
name: root
password: M5awantk
cloud:
config:
server:
git:
clone-on-start: true
uri: https://git.assembla.com/*********
username: ***********
password: ***********
Hitting http://localhost:8080/notification-service/default gives the following which is correct
{
name: "notification-service",
profiles: [
"default"
],
label: null,
version: "21ee5025b232b812e0e64387cd577eeda0351214",
state: null,
propertySources: [
{
name: "https://git.assembla.com/pins-configuration.git/notification-service.yml",
source: {
spring.main.allow-bean-definition-overriding: true,
spring.application.name: "notification-service",
spring.zipkin.baseUrl: "http://localhost:9411/",
spring.jpa.properties.hibernate.cache.use_second_level_cache: true,
spring.jpa.properties.hibernate.cache.use_query_cache: true,
server.port: 8091,
server.compression.enabled: true,
server.compression.min-response-size: 2048,
server.compression.mime-types: "application/json,application/xml,text/html,text/plain",
eureka.instance.hostname: "localhost",
eureka.instance.port: 8761,
eureka.instance.leaseRenewalIntervalInSeconds: 3,
eureka.instance.instanceId:
"${spring.application.name}:${spring.application.instance_id:${random.value}}",
eureka.client.registryFetchIntervalSeconds: 5,
eureka.client.instanceInfoReplicationIntervalSeconds: 5,
eureka.client.initialInstanceInfoReplicationIntervalSeconds: 5,
eureka.client.serviceUrl.defaultZone:
"http://${eureka.instance.hostname}:${eureka.instance.port}/eureka/"
}
}
]
}
Client (named notification-service)
Client bootstrap.yml
spring:
cloud:
config:
uri: http://localhost:8888
username: root
password: M5awantk
name: notification-service
application:
name: notifcation-service
On staring the notification-service it seems to find the config service and the notification-service.yml as expected but then we get an error
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
Although we have the following in notification-service.yml and it shows when we hit http://localhost:8080/notification-service/default
spring.main.allow-bean-definition-overriding: true
Console output when starting notification-service
2020-03-24 18:26:03.046 INFO [notifcation-service,,,] 24238 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
2020-03-24 18:26:04.847 INFO [notifcation-service,,,] 24238 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Located environment: name=notification-service, profiles=[default], label=null, version=21ee5025b232b812e0e64387cd577eeda0351214, state=null
2020-03-24 18:26:04.848 INFO [notifcation-service,,,] 24238 --- [ main] b.c.PropertySourceBootstrapConfiguration : Located property source: OriginTrackedCompositePropertySource {name='configService', propertySources=[MapPropertySource {name='configClient'}, OriginTrackedMapPropertySource {name='https://git.assembla.com/pins-configuration.git/notification-service.yml'}]}
2020-03-24 18:26:04.900 INFO [notifcation-service,,,] 24238 --- [ main] c.s.p.n.NotificationServiceApplication : The following profiles are active: dev
2020-03-24 18:26:06.237 INFO [notifcation-service,,,] 24238 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-03-24 18:26:06.464 INFO [notifcation-service,,,] 24238 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 217ms. Found 3 JPA repository interfaces.
2020-03-24 18:26:06.474 INFO [notifcation-service,,,] 24238 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-03-24 18:26:06.615 INFO [notifcation-service,,,] 24238 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 140ms. Found 21 JPA repository interfaces.
2020-03-24 18:26:06.616 WARN [notifcation-service,,,] 24238 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'jpaAuditingHandler' defined in null: Cannot register bean definition [Root bean: class [org.springframework.data.auditing.AuditingHandler]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] for bean 'jpaAuditingHandler': There is already [Root bean: class [org.springframework.data.auditing.AuditingHandler]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] bound.
2020-03-24 18:26:06.626 INFO [notifcation-service,,,] 24238 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-24 18:26:06.630 ERROR [notifcation-service,,,] 24238 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'jpaAuditingHandler' could not be registered. A bean with that name has already been defined and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
Not sure what we might be doing wrong.
EDIT: I have managed to get a very simple application working with just one property set in the corresponding application.yml.
Wondering if it is something to do with properties not being available in time, although from the console output that would not appear to be the case.

Related

Spring Cloud Config Client Located Server: properties not loaded

I am sure this is some kind of boot/cloud version dependency issue but I can't figure out the combination of dependencies and property values.
Config Servers starts and properties are available in browser
localhost:8888/master/ucdp-ingest
localhost:8888/master/ucdp-ingest-dev
$ java --version
openjdk 11.0.14.1 2022-02-08 LTS
OpenJDK Runtime Environment Corretto-11.0.14.10.1 (build 11.0.14.1+10-LTS)
OpenJDK 64-Bit Server VM Corretto-11.0.14.10.1 (build 11.0.14.1+10-LTS, mixed mode)
Therefore according to 2021-0-3 Availability and the java version we use, went with
Spring Boot: 2.7.6
Spring Cloud: 2021.0.3
Client pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.6</version>
<relativePath/>
</parent>
<properties>
<aws-sdk.version>1.12.368</aws-sdk.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<jacoco.version>0.8.8</jacoco.version>
<jasypt-spring-boot.version>3.0.5</jasypt-spring-boot.version>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<spring-cloud.version>2021.0.3</spring-cloud.version>
<spring-cloud-stream-kinesis-binder.version>2.2.0</spring-cloud-stream-kinesis-binder.version>
<springdoc-openapi-ui.version>1.6.14</springdoc-openapi-ui.version>
<swagger-maven-plugin.version>2.1.6</swagger-maven-plugin.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- Spring cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
Note no "spring-cloud-starter-bootstrap" per documentation.
Interestingly "spring.profiles.active" shows deprecated.
However, according to Spring 2.4 docs it should be spring.config.activate.on-profile. This doesn't resolve as system property.
-Dspring.config.activate.on-profile=dev
2022-12-23 15:28:51.358 INFO 36316 --- [ main] c.b.u.ucdp.ingest.UcdpIngestApplication : No active profile set, falling back to 1 default profile: "default"
Client: application.yml
spring:
application:
name: ucdp-ingest
cloud:
config:
name: ${spring.application.name}
uri: http://localhost:8888
username: ----------
password: ---------
request-connect-timeout: 3000
request-read-timeout: 3000
retry:
initial-interval: 1000
max-attempts: 6
label: master
fail-fast: true
config:
import: "configserver:"
server:
port: 8300
servlet:
context-path: /${spring.application.name}
# Actuator
management:
#opt-in use enabled-by-default: false then enable what you want. default = true
enabled-by-default: true
server:
port: ${server.port}
endpoints:
web:
base-path: ${server.servlet.context-path}
exposure:
include: "*"
endpoint:
env:
enabled: true
health:
show-details: always
enabled: true
info:
enabled: true
# shutdown:
# enabled: true
#OpenAPI
springdoc:
api-docs:
path: /docs/api-docs
version: openapi_3_1
swagger-ui:
path: /docs/swagger-ui
paths-to-match: /**
REMOTE application-ucdp-ingest.yml
app:
ucdp:
url: https://ucdpapi.pcr.uu.se/api
connect-timeout-millis: 2000
read-timeout-seconds: 2000
ged:
job:
enabled: true
cron: "20 49 11 * * ?"
#Max page size is 1000
pageSize: 1000
uri: /gedevents/21.1
REMOTE application-ucdp-ingest-dev.yml
contains mongo and aws connection properties. Mongo also failed to connect because properties were not loaded remotely.
LOGS: Note I am passing profile as system property.
+ /c/sfw/java/jdk11.0.14_10/bin/java -Dspring.config.activate.on-profile=dev -Dlogging.config=/c/projects/ucdp-ingest/ucdp-ingest-app/config/logback.xml -jar /c/projects/ucdp-ingest/ucdp-ingest-app/target/ucdp-ingest-app-0.0.1-SNAPSHOT.jar
2022-12-23 15:30:50.081 INFO 20496 --- [ main] c.b.u.ucdp.ingest.UcdpIngestApplication : Starting UcdpIngestApplication v0.0.1-SNAPSHOT using Java 11.0.14.1 on BRANDA-BSTAQ-PC with PID 20496 (C:\projects\ucdp-ingest\ucdp-ingest-app\target\ucdp-ingest-app-0.0.1-SNAPSHOT.jar started by BruceRandall in C:\projects\ucdp-ingest\ucdp-ingest-app)
2022-12-23 15:30:50.086 INFO 20496 --- [ main] c.b.u.ucdp.ingest.UcdpIngestApplication : The following 1 profile is active: "dev"
2022-12-23 15:30:50.136 INFO 20496 --- [ main] o.s.c.c.c.ConfigServerConfigDataLoader : Fetching config from server at : http://localhost:8888
2022-12-23 15:30:50.137 INFO 20496 --- [ main] o.s.c.c.c.ConfigServerConfigDataLoader : Located environment: name=ucdp-ingest, profiles=[dev], label=master, version=7102644c36175df62e3a3952793021cdf730583a, state=null
2022-12-23 15:30:51.495 INFO 20496 --- [ main] ptablePropertiesBeanFactoryPostProcessor : Post-processing PropertySource instances
2022-12-23 15:30:51.496 INFO 20496 --- [ main] c.u.j.EncryptablePropertySourceConverter : Skipping PropertySource configurationProperties [class org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertySource
2022-12-23 15:30:51.498 INFO 20496 --- [ main] c.u.j.EncryptablePropertySourceConverter : Skipping PropertySource servletConfigInitParams [class org.springframework.core.env.PropertySource$StubPropertySource
2022-12-23 15:30:51.498 INFO 20496 --- [ main] c.u.j.EncryptablePropertySourceConverter : Skipping PropertySource servletContextInitParams [class org.springframework.core.env.PropertySource$StubPropertySource
2022-12-23 15:30:51.499 INFO 20496 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource systemProperties [org.springframework.core.env.PropertiesPropertySource] to EncryptableMapPropertySourceWrapper
2022-12-23 15:30:51.499 INFO 20496 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource systemEnvironment [org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor$OriginAwareSystemEnvironmentPropertySource] to EncryptableSystemEnvironmentPropertySourceWrapper
2022-12-23 15:30:51.500 INFO 20496 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource random [org.springframework.boot.env.RandomValuePropertySource] to EncryptablePropertySourceWrapper
2022-12-23 15:30:51.500 INFO 20496 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource cachedrandom [org.springframework.cloud.util.random.CachedRandomPropertySource] to EncryptablePropertySourceWrapper
2022-12-23 15:30:51.500 INFO 20496 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource springCloudClientHostInfo [org.springframework.core.env.MapPropertySource] to EncryptableMapPropertySourceWrapper
2022-12-23 15:30:51.500 INFO 20496 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource configClient [org.springframework.core.env.MapPropertySource] to EncryptableMapPropertySourceWrapper
2022-12-23 15:30:51.500 INFO 20496 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource Config resource 'file [config\application.yml]' via location 'optional:file:./config/' [org.springframework.boot.env.OriginTrackedMapPropertySource] to EncryptableMapPropertySourceWrapper
2022-12-23 15:30:51.664 INFO 20496 --- [ main] c.u.j.filter.DefaultLazyPropertyFilter : Property Filter custom Bean not found with name 'encryptablePropertyFilter'. Initializing Default Property Filter
2022-12-23 15:30:51.673 INFO 20496 --- [ main] c.u.j.r.DefaultLazyPropertyResolver : Property Resolver custom Bean not found with name 'encryptablePropertyResolver'. Initializing Default Property Resolver
2022-12-23 15:30:51.675 INFO 20496 --- [ main] c.u.j.d.DefaultLazyPropertyDetector : Property Detector custom Bean not found with name 'encryptablePropertyDetector'. Initializing Default Property Detector
2022-12-23 15:30:52.246 INFO 20496 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8300 (http)
2022-12-23 15:30:52.256 INFO 20496 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-12-23 15:30:52.256 INFO 20496 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.69]
2022-12-23 15:30:52.351 INFO 20496 --- [ main] o.a.c.c.C.[.[localhost].[/ucdp-ingest] : Initializing Spring embedded WebApplicationContext
2022-12-23 15:30:52.351 INFO 20496 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2212 ms
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gedJob' defined in URL [jar:file:/C:/projects/ucdp-ingest/ucdp-ingest-app/target/ucdp-ingest-app-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/com/bar/udl/ucdp/ingest/service/impl/GedJob.class]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid #Scheduled method 'executeJob':
Could not resolve placeholder 'app.ged.job.cron' in value "${app.ged.job.cron}"
ConfigServerConfigDataLoader : Located environment: name=ucdp-ingest, profiles=[dev], label=master, version=7102644c36175df62e3a3952793021cdf730583a, state=null
Could not resolve placeholder 'app.ged.job.cron' in value "${app.ged.job.cron}"
Unfortunately, ConfigServerConfigDataLoader doesn't give you a complete URL
Configuration Server Endpoint
http://localhost:8888/master/ucdp-ingest
{
"name": "master",
"profiles": [
"ucdp-ingest"
],
"label": null,
"version": "155b907870c49c194dee1f1b6d94be768ce043ec",
"state": null,
"propertySources": [
{
"name": "C:\\\\projects\\\\udl-app-config/file:C:\\Users\\BRUCER~1\\AppData\\Local\\Temp\\config-repo-1334124828626900950\\application-ucdp-ingest.yml",
"source": {
"app.ucdp.url": "https://ucdpapi.pcr.uu.se/api",
"app.ucdp.connect-timeout-millis": 2000,
"app.ucdp.read-timeout-seconds": 2000,
"app.ged.job.enabled": true,
"app.ged.job.cron": "20 49 11 * * ?",
"app.ged.pageSize": 1000,
"app.ged.uri": "/gedevents/21.1",
}
}
]
Reverted back to boot 2.4.3, cloud 2020.0.3 but will be working back up to boot 2.7.6 cloud 2021.0.3.
The main issue was incorrectly interpreting the specification for the naming convention for property files. I noticed when querying the configuration server the name was the branch and the profile was the application name. Hence the reason I could only pull properties with localhost:8888/master/app-name-profile
Once I removed application from my file names in the git repository to ${spring.application.name}-profile I was able to query the server correctly and
the client was able to connect and load properties.
My last issue is I can't pass the profile in as a system property -Dspring.profiles.active=dev resolves to default when the bean access the Config Server.

Spring boot H2 console returns 404

I have a simple Springboot application and it's up running. I am able to call REST endpoints through Postman. However, when I try to access the console using http://localhost:8080/h2 it keeps returning 404.
2020-08-29 08:06:37.577 INFO 6507 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2020-08-29 08:06:37.644 INFO 6507 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.2.17.Final}
2020-08-29 08:06:37.645 INFO 6507 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2020-08-29 08:06:37.677 INFO 6507 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2020-08-29 08:06:37.787 INFO 6507 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-08-29 08:06:38.247 INFO 6507 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-08-29 08:06:38.737 INFO 6507 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2020-08-29 08:06:38.738 INFO 6507 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2020-08-29 08:06:38.741 INFO 6507 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2020-08-29 08:06:38.813 INFO 6507 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2020-08-29 08:06:38.813 INFO 6507 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2020-08-29 08:06:38.816 INFO 6507 --- [ main] c.v.t.c.m.tenant.discovery.Application : Started Application in 3.4 seconds (JVM running for 3.661)
2020-08-29 08:06:48.527 WARN 6507 --- [ctor-http-nio-2] .a.w.r.e.DefaultErrorWebExceptionHandler : Failed to handle request [GET http://localhost:8080/h2]: Response status 404
2020-08-29 08:23:07.301 WARN 6507 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Retrograde clock change detected (housekeeper delta=29s626ms), soft-evicting connections from pool.
2020-08-29 08:57:06.586 WARN 6507 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Thread starvation or clock leap detected (housekeeper delta=33m59s284ms).
2020-08-29 09:35:49.699 WARN 6507 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Thread starvation or clock leap detected (housekeeper
My application.yml file looks like this.
spring:
datasource:
url: jdbc:h2:mem:test
platform: h2
username: sa
password:
driverClassName: org.h2.Driver
hikari:
maximum-pool-size: 50
h2:
console:
enabled: true
path: /h2
settings:
web-allow-others: true
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: update
server:
port: 8080
As per your logs, I found that, you are using an embedded server, other than tomcat, i.e, spring-boot-starter-reactor-netty that comes along with spring webflux dependency.
H2ConsoleAutoConfiguration will not be executed for spring webflux & netty(reactor based), as H2 console will only be available to servlet based applications. So, you have to configure H2 server manually in this spring boot application, with spring webflux & netty.
Sample H2Server (working code):
package com.example.springbootnettyserver;
import org.h2.tools.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import static org.h2.tools.Server.createWebServer;
#Component
public class H2ServerManual {
Logger log = LoggerFactory.getLogger(H2ServerManual.class);
private Server webServer;
#Value("${h2-server.port}")
Integer h2ConsolePort;
#EventListener(ContextRefreshedEvent.class)
public void start() throws java.sql.SQLException {
log.info("starting h2 console at port "+ h2ConsolePort);
this.webServer = createWebServer("-webPort", h2ConsolePort.toString(),
"-tcpAllowOthers").start();
System.out.println(webServer.getURL());
}
#EventListener(ContextClosedEvent.class)
public void stop() {
log.info("stopping h2 console at port "+h2ConsolePort);
this.webServer.stop();
}
}
Note: org.h2.tools.Server class will be resolved only when h2 dependency is added without scope of runtime. (remove scope element in dependency)
In application.properties, you will add port details for h2 server like
h2-server:
port: 8081
Here, now, the H2 console will be available at http://localhost:8081
Following properties can be removed
# h2:
# console:
# enabled: true
# path: /h2
# settings:
# web-allow-others: true
For Reference: https://github.com/donthadineshkumar/webflux-netty-server-h2-example.git

How to move Zuul gateway configurations to configuration server

I'm starting out with microservices architecture and spring cloud.
I'm trying to get configurations for my Spring Zuul Gateway from the spring configuration server.
I've added below properties in bootstrap.properties file of the gateway service:
spring.application.name=api-gateway
spring.cloud.config.uri=http://localhost:8888
spring.profiles.active=dev
Even though these properties work for all other services, for the gateway they do not work.
The annotations I'm using for the gateway are:
#EnableZuulProxy
#EnableDiscoveryClient
#SpringBootApplication
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
The annotation for other services is only:
#SpringBootApplication
My configuration server has a connected git repository with a file: api-gateway-dev.properties
logs of gateway:
:: Spring Boot :: (v2.3.0.M4)
2020-04-17 21:42:39.983 INFO 10340 --- [ restartedMain]
c.nyo.apigateway.ApiGatewayApplication : The following profiles are
active: dev 2020-04-17 21:42:41.926 WARN 10340 --- [ restartedMain]
o.s.boot.actuate.endpoint.EndpointId : Endpoint ID
'service-registry' contains invalid characters, please migrate to a
valid format. 2020-04-17 21:42:41.969 WARN 10340 --- [
restartedMain] o.s.boot.actuate.endpoint.EndpointId : Endpoint ID
'hystrix.stream' contains invalid characters, please migrate to a
valid format. 2020-04-17 21:42:42.240 INFO 10340 --- [
restartedMain] o.s.cloud.context.scope.GenericScope : BeanFactory
id=a11a283e-7de6-3470-b177-65c08eab7398 2020-04-17 21:42:43.859 INFO
10340 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer :
Tomcat initialized with port(s): 8765 (http) 2020-04-17 21:42:43.880
INFO 10340 --- [ restartedMain]
o.apache.catalina.core.StandardService : Starting service [Tomcat]
logs of a service that is getting configurations:
:: Spring Boot :: (v2.3.0.M4)
2020-04-17 21:54:01.414 INFO 5180 --- [ restartedMain]
c.c.c.ConfigServicePropertySourceLocator : Fetching config from server
at : http://localhost:8888 2020-04-17 21:54:04.184 INFO 5180 --- [
restartedMain] c.c.c.ConfigServicePropertySourceLocator : Located
environment: name=users-service, profiles=[dev], label=null,
version=244114f5a11aa7d4a0acb5750ddad144f7de1be5, state=null
2020-04-17 21:54:04.186 INFO 5180 --- [ restartedMain]
b.c.PropertySourceBootstrapConfiguration : Located property source:
[BootstrapPropertySource {name='bootstrapProperties-configClient'},
BootstrapPropertySource
{name='bootstrapProperties-https://my-user#bitbucket.org/my-user/configs.git/users-service-dev.properties'},
BootstrapPropertySource
{name='bootstrapProperties-https://my-user#bitbucket.org/my-user/configs.git/users-service.properties'}]
2020-04-17 21:54:04.197 INFO 5180 --- [ restartedMain]
c.n.U.UsersServiceApplication : The following profiles are
active: dev
Is it logical to make gateway configuration dynamic?
Why don't I get the configuration from the configuration server?
Found the problem. I was missing:
implementation 'org.springframework.cloud:spring-cloud-starter-config'
in my build.gradle file dependencies

Unable to hit rest service running with spring boot

I have configured restful webservice and hosted with the help of Spring Boot. But I'm not able to hit the service. And getting Response Status: -1 - Request Failed (Canceled or Timed-Out)
Logs:-
⁃ 2017-10-08 18:33:33.149 INFO 6806 --- [ main] com.mypleaks.PleaksRSApp : Starting PleaksRSApp on 3inmderaj1.local with PID 6806 (/Users/deraj/home/code/leaks-rs/mypleaks-rs/myPleaks-RS/target/classes started by deraj in /Users/deraj/home/code/leaks-rs/mypleaks-rs/myPleaks-RS)
⁃ 2017-10-08 18:33:33.155 INFO 6806 --- [ main] com.mypleaks.PleaksRSApp : No active profile set, falling back to default profiles: default
⁃ 2017-10-08 18:33:33.202 INFO 6806 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#311bf055: startup date [Sun Oct 08 18:33:33 IST 2017]; root of context hierarchy
⁃ 2017-10-08 18:33:33.998 INFO 6806 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'requestContextFilter' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration; factoryMethodName=requestContextFilter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.class]] with [Root bean: class [org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=requestContextFilter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
⁃ 2017-10-08 18:33:34.276 INFO 6806 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
⁃ 2017-10-08 18:33:34.372 INFO 6806 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$af71e9e1] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
⁃ 2017-10-08 18:33:34.745 INFO 6806 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
⁃ 2017-10-08 18:33:34.756 INFO 6806 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
⁃ 2017-10-08 18:33:34.756 INFO 6806 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.6
Resource :-
Request:-
Response:-
It seems that you are using the annotations from the javax. package instead of the spring ones.
Try using #RestController on the class level and #RequestMapping on the method level (all other annotations should be from the spring package also):
#RestController
#RequestMapping(path = "/place")
public class PlaceResource{
#RequestMapping(method = RequestMethod.GET, path="/countries")
public Response getCountries(..){..}
}
Sorry Guys, Its was terrible mistake from my side. I had used below code in my application.
public class NotificationEngine implements InitializingBean {
#Override
public void afterPropertiesSet() throws Exception {"Here I was running some stupid endless process, Due to which the tomcat was not getting up completely and because of that Iwas getting this issue."}}
Please check that you have following dependency in your pom.xml, If it is not there please add it and re-run.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Error connecting to database Spring boot

Helo I have been trying to connect to a database with Spring Boot for a while and I keep getting the error:
java.sql.SQLException: The url cannot be null
I am not sure what is it that I am doing wrong. The reason I am trying to get the configuration like this is because I want to use the encoded password for the database.
This is what my files look like:
DataConfig.java
#Configuration
public class DataConfig {
#Autowired
private Environment env;
#Configuration
#Profile(value = "dev")
public class DevPlaceHolderConfig {
#Bean
DataSource dataSource() {
return DataSourceBuilder
.create()
.username(env.getProperty("spring.datasource.username"))
.password(env.getProperty("spring.datasource.password"))
.url(env.getProperty("spring.datasource.url"))
.driverClassName(env.getProperty("spring.datasource.driver-class-name"))
.build();
}
}
#Configuration
#Profile(value = "prod")
public class ProdPlaceHolderConfig {
#Bean
DataSource dataSource() {
return DataSourceBuilder
.create()
.username(env.getProperty("spring.datasource.username"))
.password(env.getProperty("spring.datasource.password"))
.url(env.getProperty("spring.datasource.url"))
.driverClassName(env.getProperty("spring.datasource.driver-class-name"))
.build();
}
}
}
EncryptorConfig.java
#Configuration
public class EncryptorConfig {
#Bean
public EnvironmentStringPBEConfig environmentVariablesConfiguration() {
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
config.setPasswordEnvName("APP_ENCRYPTION_PASSWORD");
return config;
}
#Bean
public PooledPBEStringEncryptor stringEncryptor() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
encryptor.setConfig(environmentVariablesConfiguration());
return encryptor;
}
}
application.yml
spring:
profiles:
active: prod
output:
ansi:
enabled: always
---
spring:
profiles: dev
application:
name: App-Dev
datasource:
url: jdbc:mysql://localhost:3306/database?useSSL=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
jpa:
show-sql: true
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
server:
port: 8080
---
spring:
profiles: prod
application:
name: App-Prod
datasource:
url: jdbc:mysql://localhost:3306/database?useSSL=false
username: root
password: ENC(/98CfxmsjKBW5oZsLkLlmw==)
driver-class-name: com.mysql.jdbc.Driver
jpa:
show-sql: true
hibernate:
ddl-auto: none
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
server:
port: 3000
Here is the stack trace
2017-09-04 09:20:02.476 INFO 18128 --- [ main] com.vir.VirBackendApplication : The following profiles are active: prod
2017-09-04 09:20:02.536 INFO 18128 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#1ebd319f: startup date [Mon Sep 04 09:20:02 EDT 2017]; root of context hierarchy
2017-09-04 09:20:03.479 INFO 18128 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=com.vir.config.DataConfig$ProdPlaceHolderConfig; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/vir/config/DataConfig$ProdPlaceHolderConfig.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=com.vir.config.EncryptorConfig$ProdPlaceHolderConfig; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/vir/config/EncryptorConfig$ProdPlaceHolderConfig.class]]
2017-09-04 09:20:03.898 INFO 18128 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-09-04 09:20:04.112 INFO 18128 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$55ffc8cc] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-09-04 09:20:04.421 INFO 18128 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 5000 (http)
2017-09-04 09:20:04.431 INFO 18128 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-09-04 09:20:04.432 INFO 18128 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-09-04 09:20:04.589 INFO 18128 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-09-04 09:20:04.589 INFO 18128 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2055 ms
2017-09-04 09:20:04.764 INFO 18128 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-04 09:20:04.769 INFO 18128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-04 09:20:04.769 INFO 18128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-04 09:20:04.769 INFO 18128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-04 09:20:04.769 INFO 18128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-04 09:20:04.817 INFO 18128 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2017-09-04 09:20:04.820 INFO 18128 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-09-04 09:20:04.821 INFO 18128 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-09-04 09:20:04.967 WARN 18128 --- [ main] o.a.tomcat.jdbc.pool.PooledConnection : Not loading a JDBC driver as driverClassName property is null.
2017-09-04 09:20:04.978 ERROR 18128 --- [ main] o.a.tomcat.jdbc.pool.ConnectionPool : Unable to create initial connections of pool.
java.sql.SQLException: The url cannot be null
at java.sql.DriverManager.getConnection(Unknown Source) ~[na:1.8.0_144]
at java.sql.DriverManager.getConnection(Unknown Source) ~[na:1.8.0_144]
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:308) ~[tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:203) ~[tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:735) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:667) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:482) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:154) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:118) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:107) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:131) [tomcat-jdbc-8.5.16.jar:na]
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) [spring-jdbc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) [spring-jdbc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:326) [spring-jdbc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:366) [spring-jdbc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.boot.autoconfigure.orm.jpa.DatabaseLookup.getDatabase(DatabaseLookup.java:72) [spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.autoconfigure.orm.jpa.JpaProperties.determineDatabase(JpaProperties.java:139) [spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter(JpaBaseConfiguration.java:105) [spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$bf862cec.CGLIB$jpaVendorAdapter$9(<generated>) [spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$bf862cec$$FastClassBySpringCGLIB$$3d2e4b4f.invoke(<generated>) [spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) [spring-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) [spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$bf862cec.jpaVendorAdapter(<generated>) [spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_144]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_144]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_144]
Ok so it took me a while but this is how I solved my issues; which turned out to be a few.
Make sure you include a property placeholder in the configuration so then the actual property value can bind to.
Make sure to read about it here enter link description here
So now my application.yml file looks like bellow, and APP_ENCRYPTION_PASSWORD is an environment variable holding the encryption password.
spring:
profiles:
active: prod
output:
ansi:
enabled: detect
---
spring:
profiles: dev
application:
name: App-Dev
datasource:
url: jdbc:mysql://localhost:3306/database?useSSL=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
jpa:
show-sql: true
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
server:
port: 8080
---
spring:
profiles: prod
application:
name: App-Prod
datasource:
url: jdbc:mysql://localhost:3306/database?useSSL=false
username: root
password: ENC(/98CfxmsjKBW5oZsLkLlmw==)
driver-class-name: com.mysql.jdbc.Driver
jpa:
show-sql: true
hibernate:
ddl-auto: none
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
jasypt:
encryptor:
algorithm: PBEWithMD5AndDES
password: ${APP_ENCRYPTION_PASSWORD}
server:
port: 3000
Only one data source configuration bean needed. I have it set to change active profiles so the correct configuration is picked.
Also create private variables and bind them with a #Value() annotation. Also add the #EnableEncryptableProperties to the class.
DataConfig.java
#Configuration
#EnableEncryptableProperties
public class DataConfig {
#Value("${spring.datasource.username}")
private String userName;
#Value("${spring.datasource.password}")
private String password;
#Value("${spring.datasource.url}")
private String url;
#Value("${spring.datasource.driver-class-name}")
private String driverClassName;
#Bean
DataSource dataSource() {
return DataSourceBuilder
.create()
.username(userName)
.password(password)
.url(url)
.driverClassName(driverClassName)
.build();
}
}
And that's it it solved all my problems.

Resources