Spring cloude: Zuul & consul - spring-cloud

I'm trying to create a Spring cloud microservice application using Zuul and Consul.
I have 2 components in my project:
api-gateway microservice using Zuul
Hello world microservice (a simple hello world Rest Webservice)
Here is the code of The api-gateway:
#SpringBootApplication
#EnableZuulProxy
#EnableDiscoveryClient
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
The pom.xml
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.M3</version>
</parent>
<properties>
<java.version>1.8</java.version>
<spring.cloud.consul.version>1.0.0.BUILD-SNAPSHOT</spring.cloud.consul.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
</dependency>
<dependency>
<!-- Setup Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<!-- Setup Spring MVC & REST, use Embedded Tomcat -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<!-- Spring Cloud starter -->
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-all</artifactId>
<version>${spring.cloud.consul.version}</version>
</dependency>
</dependencies>
application.yml
zuul:
routes:
hello1:
path: /hello1/**
serviceId: microservice-example
logging:
level:
org.springframework: INFO
com.netflix: DEBUG
bootstrap.yml
spring:
application:
name: edge-server
cloud:
consul:
config:
enabled: true
host: localhost
port: 8500
Here is the code of hello microservice:
#SpringBootApplication
#EnableConfigServer
#EnableDiscoveryClient
#RestController
public class Application {
#RequestMapping(value="/hello1",method = RequestMethod.GET)
public String hello() {
System.out.print("hello1");
return "Hello1";
}
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
bootstrap.yml:
spring:
application:
name: microservice-example
profiles:
active: native
cloud:
consul:
config:
enabled: true
host: localhost
port: 8500
But, when I test my service the browser shows this message:
Here is the stacktrace of edge-server application:
2015-11-25 16:49:31.780 DEBUG 9876 --- [nio-8080-exec-7] c.n.zuul.http.HttpServletRequestWrapper : Path = null
2015-11-25 16:49:31.781 DEBUG 9876 --- [nio-8080-exec-7] c.n.zuul.http.HttpServletRequestWrapper : Transfer-Encoding = null
2015-11-25 16:49:31.781 DEBUG 9876 --- [nio-8080-exec-7] c.n.zuul.http.HttpServletRequestWrapper : Content-Encoding = null
2015-11-25 16:49:31.781 DEBUG 9876 --- [nio-8080-exec-7] c.n.zuul.http.HttpServletRequestWrapper : Content-Length header = -1
2015-11-25 16:49:31.782 DEBUG 9876 --- [nio-8080-exec-7] c.n.loadbalancer.ZoneAwareLoadBalancer : Zone aware logic disabled or there is only one zone
2015-11-25 16:49:31.782 DEBUG 9876 --- [nio-8080-exec-7] c.n.loadbalancer.LoadBalancerContext : microservice-example using LB returned Server: FR09248851D:1234 for request
2015-11-25 16:49:31.783 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.niws.client.http.RestClient : RestClient sending new Request(GET: ) http://FR09248851D:1234
2015-11-25 16:49:31.783 DEBUG 9876 --- [nio-8080-exec-7] c.n.http4.MonitoredConnectionManager : Get connection: {}->http://FR09248851D:1234, timeout = 2000
2015-11-25 16:49:31.783 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NamedConnectionPool : [{}->http://FR09248851D:1234] total kept alive: 1, total issued: 0, total allocated: 1 out of 200
2015-11-25 16:49:31.783 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NamedConnectionPool : Getting free connection [{}->http://FR09248851D:1234][null]
2015-11-25 16:49:31.783 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NFHttpClient : Stale connection check
2015-11-25 16:49:31.784 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NFHttpClient : Attempt 1 to execute request
2015-11-25 16:49:31.791 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NFHttpClient : Connection can be kept alive indefinitely
2015-11-25 16:49:31.796 DEBUG 9876 --- [nio-8080-exec-7] c.n.http4.MonitoredConnectionManager : Released connection is reusable.
2015-11-25 16:49:31.796 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NamedConnectionPool : Releasing connection [{}->http://FR09248851D:1234][null]
2015-11-25 16:49:31.796 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NamedConnectionPool : Pooling connection [{}->http://FR09248851D:1234][null]; keep alive indefinitely
2015-11-25 16:49:31.796 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NamedConnectionPool : Notifying no-one, there are no waiting threads
2015-11-25 16:49:35.721 DEBUG 9876 --- [service-example] c.netflix.loadbalancer.BaseLoadBalancer : LoadBalancer: PingTask executing [1] servers configured
2015-11-25 16:49:35.885 DEBUG 9876 --- [clean up thread] com.netflix.http4.ConnectionPoolCleaner : Connection pool clean up started for client microservice-example
2015-11-25 16:49:35.885 DEBUG 9876 --- [clean up thread] c.n.http4.MonitoredConnectionManager : Closing expired connections

Related

Consul not load property in spring boot application spring.config

How do I configure spring boot aplication and consul? I read a oficial documentation but i cant do it...
pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>11</java.version>
<spring-cloud.version>2021.0.0</spring-cloud.version>
</properties>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-vault-config</artifactId>
</dependency>
application.yml
spring:
application:
name: gateway
config:
import:
- "vault://secret"
- "consul:127.0.0.1:8500"
cloud:
vault:
scheme: http
authentication: TOKEN
host: 127.0.0.1
port: 8200
token: myroot
connection-timeout: 5000
read-timeout: 15000
consul:
config:
enabled: true
prefix: config
format: yaml
profile-separator: ","
watch:
enabled: true
Test property
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MyController {
#Value("${test}")
String myConsule1;
#GetMapping("/mycontroller")
public String getValues() {
return "{v1: '" + myConsule1 + "', v2: '" + "" + "'}";
}
}
Consul
ERROR:
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'test' in value "${test}"
Can you help me? please...

I can't map the Rest Endpoint with Spring Boot

I'm starting work with SpringBoot in a new project, and I'm trying create a environment like a base.
So, I'm mappping the endpoins, but when I iniciality the server, I can see that those endpoint don't load.
My Rest Class
#RestController
#RequestMapping("/estados")
public class EstadoResource {
#Autowired private EstadoRepository estadoRepository;
#RequestMapping(value = "/criar", method = RequestMethod.GET)
public String criar() {
Estado estado = new Estado();
estado.setNome("Rio de Janeiro");
return "Rest Funcionando";
}
}
I tried with #GetMapping and didn't work too.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.apppet.backend</groupId>
<artifactId>app-pet</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app-pet</name>
<description>Aplicacao Backend Pet</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.xml
spring.datasource.url=jdbc:postgresql://localhost:5432/app_pet
spring.datasource.username=app_pet
spring.datasource.password=
logging.level.web=DEBUG
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Main Class
#SpringBootApplication
public class App4petApplication {
public static void main(String[] args) {
SpringApplication.run(App4petApplication.class, args);
}
}
Spring Console
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.5.RELEASE)
2020-03-22 00:15:17.148 INFO 12893 --- [ restartedMain] c.a.backend.apppet.ApppetApplication : Starting ApppetApplication on gustavo-rey with PID 12893 (/home/gustavo-rey/Pet/Backend/target/classes started by gustavo-rey in /home/gustavo-rey/Pet/Backend)
2020-03-22 00:15:17.152 INFO 12893 --- [ restartedMain] c.a.backend.apppet.ApppetApplication : No active profile set, falling back to default profiles: default
2020-03-22 00:15:17.249 INFO 12893 --- [ restartedMain] o.s.b.devtools.restart.ChangeableUrls : The Class-Path manifest attribute in /home/gustavo-rey/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jaxb-runtime-2.3.2.jar referenced one or more files that do not exist: file:/home/gustavo-rey/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.xml.bind-api-2.3.2.jar,file:/home/gustavo-rey/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/txw2-2.3.2.jar,file:/home/gustavo-rey/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/istack-commons-runtime-3.0.8.jar,file:/home/gustavo-rey/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/stax-ex-1.8.1.jar,file:/home/gustavo-rey/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/FastInfoset-1.2.16.jar,file:/home/gustavo-rey/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.activation-api-1.2.1.jar
2020-03-22 00:15:17.252 INFO 12893 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-03-22 00:15:18.061 INFO 12893 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-03-22 00:15:18.076 INFO 12893 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 9ms. Found 0 JPA repository interfaces.
2020-03-22 00:15:18.591 INFO 12893 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-22 00:15:18.601 INFO 12893 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-22 00:15:18.602 INFO 12893 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-03-22 00:15:18.727 INFO 12893 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-22 00:15:18.727 DEBUG 12893 --- [ restartedMain] o.s.web.context.ContextLoader : Published root WebApplicationContext as ServletContext attribute with name [org.springframework.web.context.WebApplicationContext.ROOT]
2020-03-22 00:15:18.727 INFO 12893 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1475 ms
2020-03-22 00:15:18.746 DEBUG 12893 --- [ restartedMain] o.s.b.w.s.ServletContextInitializerBeans : Mapping filters: characterEncodingFilter urls=[/*] order=-2147483648, formContentFilter urls=[/*] order=-9900, requestContextFilter urls=[/*] order=-105
2020-03-22 00:15:18.747 DEBUG 12893 --- [ restartedMain] o.s.b.w.s.ServletContextInitializerBeans : Mapping servlets: dispatcherServlet urls=[/]
2020-03-22 00:15:18.882 INFO 12893 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-03-22 00:15:18.932 INFO 12893 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-03-22 00:15:19.013 INFO 12893 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-03-22 00:15:19.085 INFO 12893 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-03-22 00:15:19.281 INFO 12893 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-03-22 00:15:19.298 INFO 12893 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
2020-03-22 00:15:19.644 INFO 12893 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-03-22 00:15:19.650 INFO 12893 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-03-22 00:15:19.707 WARN 12893 --- [ restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-03-22 00:15:19.830 INFO 12893 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-22 00:15:19.838 DEBUG 12893 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : ControllerAdvice beans: 0 #ModelAttribute, 0 #InitBinder, 1 RequestBodyAdvice, 1 ResponseBodyAdvice
2020-03-22 00:15:19.875 DEBUG 12893 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : 2 mappings in 'requestMappingHandlerMapping'
2020-03-22 00:15:19.904 DEBUG 12893 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Patterns [/webjars/**, /**] in 'resourceHandlerMapping'
2020-03-22 00:15:19.914 DEBUG 12893 --- [ restartedMain] .m.m.a.ExceptionHandlerExceptionResolver : ControllerAdvice beans: 0 #ExceptionHandler, 1 ResponseBodyAdvice
2020-03-22 00:15:19.996 INFO 12893 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-03-22 00:15:20.038 INFO 12893 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-03-22 00:15:20.041 INFO 12893 --- [ restartedMain] c.a.backend.apppet.ApppetApplication : Started ApppetApplication in 3.853 seconds (JVM running for 5.053)
Someone know what I can be doing it wrong?
Thanks!
Edit1: When I tried to access localhost:8080/estados/criar show the springboot white page with 404 error
Edit2: Guys, after some tests, I was able to make it work, I percebed that if I put the Main Spring Class in the same package of Controllers the system map the endpoints correctly, but I believe that is not ideal, someone know how can I configure it?

Oauth2 Client Login via Cloud Gateway gives 400 Invalid client registration id

I have a Spring Authorization/Resource server managing the authorization of a Webflux Oauth2 client. On it's own this is working OK. When I add Spring Cloud Gateway and access the Webflux via the Gateway I see that the Authorization Server validates the user and the Webflux returns 302, but on the Gateway I get 400 "Invalid client registration id".
The Authorization/Resource server is;
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
The starter;
#SpringBootApplication
#EnableAuthorizationServer
#EnableResourceServer
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Properties;
server:
port: 8889
Server configuration;
#Configuration
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private BCryptPasswordEncoder passwordEncoder;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore());
}
#Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("myClientId2")
.secret(passwordEncoder.encode("mySecret2"))
.authorizedGrantTypes("authorization_code")
.scopes("all")
.autoApprove(true)
.redirectUris("http://localhost:8083/login/oauth2/code/myAppTwo")
.and()
.withClient("myGatewayId")
.secret(passwordEncoder.encode("myGatewaySecret"))
.authorizedGrantTypes("authorization_code")
.scopes("all")
.autoApprove(true)
.redirectUris("http://localhost:8888/login/oauth2/code/gateway")
;
}
}
Security;
#Configuration
#Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and().authorizeRequests().anyRequest().authenticated()
.and().formLogin().permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("x").password(passwordEncoder().encode("123"))
.roles("USER");
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
User response;
#RestController
public class UserController {
#GetMapping("/user")
public Principal user(Principal principal) {
System.err.println(principal);
return principal;
}
The Webflux is;
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
</dependencies>
Properties;
server:
port: 8083
spring:
security:
oauth2:
client:
registration:
myAppTwo:
client-name: Test8082
client-id: myClientId2
client-secret: mySecret2
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
provider:
myAppTwo:
authorization-uri: http://localhost:8889/oauth/authorize
token-uri: http://localhost:8889/oauth/token
user-info-uri: http://localhost:8889/user
user-name-attribute: name
Webflux end point;
#RestController
public class Controller {
#GetMapping(value = "/test3")
Mono<OAuth2User> getTest3(#AuthenticationPrincipal Mono<OAuth2User> ouser) {
System.err.println("o =" + ouser);
return ouser;
}
}
Running http://localhost:8083/test3 via Chrome take me to the log-in page on the Authorization server, after which I enter the credentials and then then URL above returns the expected Response.
When I add a Gateway;
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
With properties;
server:
port: 8888
spring:
autoconfigure:
# TODO: remove when fixed https://github.com/spring-projects/spring-security/issues/17949
# Without this line, Gateway tries to log in using it's own security, rather than deferring to OAuth2
exclude: org.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration
cloud:
gateway:
routes:
- id: oauth
predicates:
- Path=/oauth2/**
uri: http://localhost:8889
filters:
- TokenRelay=
- RemoveRequestHeader=Cookie
- id: route2
predicates:
- Path=/2/**
uri: http://localhost:8083
filters:
- RewritePath=/2/(?<myPath>.*), /$\{myPath}
- TokenRelay=
- RemoveRequestHeader=Cookie
security:
oauth2:
client:
registration:
gateway:
client-id: myGatewayId
client-secret: myGatewaySecret
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
provider: gateway
provider:
gateway:
authorization-uri: http://localhost:8889/oauth/authorize
token-uri: http://localhost:8889/oauth/token
user-info-uri: http://localhost:8889/user
user-name-attribute: name
jwk-set-uri: http://localhost:8889/oauth/token_key
Now if I try http://localhost:8888/2/test3 I am still re-directed to the log-in. The toString on the Authorization server logs the credentials, the Webflux still gives 302, but the Gateway does the following;
Route matched: route2
Mapping [Exchange: GET http://localhost:8888/2/test3] to Route{id='route2', uri=http://localhost:8083, order=0, predicate=Paths: [/2/**], match trailing slash: true, gatewayFilters=[[[RewritePath /2/(?<myPath>.*) = '/${myPath}'], order = 1], [org.springframework.cloud.security.oauth2.gateway.TokenRelayGatewayFilterFactory$$Lambda$666/1724736027#4b96b22, order = 2], [[RemoveRequestHeader name = 'Cookie'], order = 3]]}
[98bb6dad] Mapped to org.springframework.cloud.gateway.handler.FilteringWebHandler#6fa90b79
Sorted gatewayFilterFactories: [[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.RemoveCachedBodyFilter#1894593a}, order = -2147483648], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter#b835727}, order = -2147482648], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.NettyWriteResponseFilter#7fd26ad8}, order = -1], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.ForwardPathFilter#7cea0110}, order = 0], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.GatewayMetricsFilter#5527b211}, order = 0], [[RewritePath /2/(?<myPath>.*) = '/${myPath}'], order = 1], [org.springframework.cloud.security.oauth2.gateway.TokenRelayGatewayFilterFactory$$Lambda$666/1724736027#4b96b22, order = 2], [[RemoveRequestHeader name = 'Cookie'], order = 3], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter#14b0e127}, order = 10000], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.config.GatewayNoLoadBalancerClientAutoConfiguration$NoLoadBalancerClientFilter#54cf7c6a}, order = 10100], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.WebsocketRoutingFilter#468dda3e}, order = 2147483646], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.NettyRoutingFilter#3d37203b}, order = 2147483647], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.ForwardRoutingFilter#10823d72}, order = 2147483647]]
"GET /2/test3 HTTP/1.1" 302 0 8888 8 ms
Resolved [ResponseStatusException: 400 BAD_REQUEST "Invalid client registration id"] for HTTP GET /oauth2/authorization/myAppTwo
Writing "<html><body><h1>Whitelabel Error Page</h1><p>This application has no configured error view, so you (truncated)...
"GET /oauth2/authorization/myAppTwo HTTP/1.1" 400 312 8888 2 ms
"GET /favicon.ico HTTP/1.1" 302 0 8888 2 ms
"GET /oauth2/authorization/gateway HTTP/1.1" 302 0 8888 2 ms
Writing form fields [grant_type, code, redirect_uri] (content masked)
Decoded [{access_token=2c14f1e7-5d95-4fed-be95-2d8518d1fb48, token_type=bearer, expires_in=40912, scope=all}]
Decoded [{authorities=[{authority=ROLE_USER}], details={remoteAddress=127.0.0.1, sessionId=null, tokenValue=2 (truncated)...]
"GET /login/oauth2/code/gateway?code=fGdiyz&state=ZynriL0UtU37b4rMfDHM7JheNYYo0UnZQvgu4U2kWwQ%3D HTTP/1.1" 302 0 8888 82 ms
"GET / HTTP/1.1" 200 3348 8888 5 ms
Via the same browser session, if I try the direct URL http://localhost:8083/test, it response correctly (i.e. I am logged in and 8083 has my credentials).
I see via debug that DefaultServerOAuth2AuthorizationRequestResolver.findByRegistrationId first checks the redirect for gateway and passes. However, it tries and fails on a second pass for the redirect of myAppTwo, which was not defined the Gateway's YML and I assume shouldn't be. Removing the route oauth seems to have no affect. I never see that route being hit.
So how do I get the Gateway to redirect to myAppTwo on port 8083?
Update When I use KeyCloak instead of my own AuthorizationServer/ResourceServer I get the same issue.

Very slow start up for Spring Boot tests with Embed Mongo DB

Even run one test you need more than 1 minute:
Startup for embed Mongo ~1 minute
test execution ~3-8 seconds
I can't understand what is the reason for such behaviour?
Following is snipped from console:
2018-12-13 13:14:43.214 INFO 12277 --- [ main] c.j.s.embedmongo.EmbeddedMongoBuilder : Initializing embedded MongoDB instance
2018-12-13 13:14:43.293 INFO 12277 --- [ main] d.f.embed.process.store.Downloader : Extract /Users/nazar/.embedmongo/osx/mongodb-osx-ssl-x86_64-3.6.5.tgz : starting...
2018-12-13 13:14:44.287 INFO 12277 --- [ main] d.f.embed.process.store.Downloader : Extract /Users/nazar/.embedmongo/osx/mongodb-osx-ssl-x86_64-3.6.5.tgz : extract mongodb-osx-x86_64-3.6.5/bin/mongod
2018-12-13 13:14:44.288 INFO 12277 --- [ main] d.f.embed.process.store.Downloader : Extract /Users/nazar/.embedmongo/osx/mongodb-osx-ssl-x86_64-3.6.5.tgz : nothing left
2018-12-13 13:14:44.288 INFO 12277 --- [ main] d.f.embed.process.store.Downloader : Extract /Users/nazar/.embedmongo/osx/mongodb-osx-ssl-x86_64-3.6.5.tgz : finished
2018-12-13 13:14:44.289 INFO 12277 --- [ main] c.j.s.embedmongo.EmbeddedMongoBuilder : Starting embedded MongoDB instance
2018-12-13 13:14:45.467 INFO 12277 --- [ main] d.f.embed.mongo.MongodExecutable : start de.flapdoodle.embed.mongo.config.MongodConfigBuilder$ImmutableMongodConfig#55fee662
2018-12-13 13:14:45.871 INFO 12277 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:50770], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-12-13 13:14:45.985 INFO 12277 --- [localhost:50770] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:1}] to localhost:50770
2018-12-13 13:14:45.990 INFO 12277 --- [localhost:50770] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:50770, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 5]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=4065087}
2018-12-13 13:14:46.627 WARN 12277 --- [ main] c.t.p.p.configuration.BugsnagConfig : Bugsnag apikey not set, not using it
2018-12-13 13:14:46.702 INFO 12277 --- [ main] c.t.p.p.c.AsyncConfigurationTest : Creating sync task executor for tests
2018-12-13 13:15:38.019 INFO 12277 --- [ Thread-7] o.s.b.a.mongo.embedded.EmbeddedMongo : note: noprealloc may hurt performance in many applications
2018-12-13 13:15:38.057 INFO 12277 --- [ Thread-7] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-12-13T13:15:38.056+0200 I CONTROL [initandlisten] MongoDB starting : pid=12460 port=50789 dbpath=/var/folders/95/6cdccp1s629gtfwm5tjb63gr0000gp/T/embedmongo-db-8535bf9e-fdc6-44f3-88c8-4bc77dd60bb3 64-bit host=sdos-MacBook-Pro.local
2018-12-13 13:15:38.057 INFO 12277 --- [ Thread-7] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-12-13T13:15:38.057+0200 I CONTROL [initandlisten] db version v3.5.5
2018-12-13 13:15:38.058 INFO 12277 --- [ Thread-7] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-12-13T13:15:38.057+0200 I CONTROL [initandlisten] git version: 98515c812b6fa893613f063dae568ff8319cbfbd
2018-12-13 13:15:38.058 INFO 12277 --- [ Thread-7] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-12-13T13:15:38.057+0200 I CONTROL [initandlisten] allocator: system
2018-12-13 13:15:38.058 INFO 12277 --- [ Thread-7] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-12-13T13:15:38.057+0200 I CONTROL [initandlisten] modules: none
2018-12-13 13:15:38.058 INFO 12277 --- [ Thread-7] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-12-13T13:15:38.057+0200 I CONTROL [initandlisten] build environment:
2018-12-13 13:15:38.058 INFO 12277 --- [ Thread-7] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-12-13T13:15:38.057+0200 I CONTROL [initandlisten] distarch: x86_64
2018-12-13 13:15:38.058 INFO 12277 --- [ Thread-7] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-12-13T13:15:38.057+0200 I CONTROL [initandlisten] target_arch: x86_64
2018-12-13 13:15:38.058 INFO 12277 --- [ Thread-7] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-12-13T13:15:38.057+0200 I CONTROL [initandlisten] options: { net: { bindIp: "127.0.0.1", http: { enabled: false }, port: 50789 }, security: { authorization: "disabled" }, storage: { dbPath: "/var/folders/95/6cdccp1s629gtfwm5tjb63gr0000gp/T/embedmongo-db-8535bf9e-fdc6-44f3-88c8-4bc77dd60bb3", journal: { enabled: false }, mmapv1: { preallocDataFiles: false, smallFiles: true }, syncPeriodSecs: 0.0 } }
Here is: full console log
It stucks the most after the line:
c.t.p.p.c.AsyncConfigurationTest: Creating sync task executor for tests
Here is a snippet from pom file:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>2.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cz.jirutka.spring</groupId>
<artifactId>embedmongo-spring</artifactId>
<version>1.3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
No additional plugins, only spring-boot-maven-plugin.
Also, no additional configuration at application.yml for tests.
Mongo configuration is next:
#Configuration
public class MongoConfig {
private static final String MONGO_DB_URL = "localhost";
private static final String MONGO_DB_NAME = "embeded_db";
#Bean
public MongoTemplate mongoTemplate() throws IOException {
EmbeddedMongoFactoryBean mongo = new EmbeddedMongoFactoryBean();
mongo.setBindIp(MONGO_DB_URL);
MongoClient mongoClient = mongo.getObject();
return new MongoTemplate(mongoClient, MONGO_DB_NAME);
}
}
Task execuotor configuration:
#Slf4j
#Configuration
#Profile("test")
public class AsyncConfigurationTest {
#Bean
#Primary
public TaskExecutor taskExecutor() {
log.info("Creating sync task executor for tests");
return new SyncTaskExecutor();
}
}
Test looks next:
#Slf4j
#SpringBootTest
#ActiveProfiles("test")
#RunWith(SpringRunner.class)
public class ServiceTest extends BaseDataServiceTest {
#Value("classpath:enter/enter_file.pdf")
private Resource enterPdf;
#Value("classpath:enter/expected.json")
private Resource enterExpectedJson;
#Test
public void testEnterDemoDocument() {
testHelper(enterPdf, enterExpectedJson);
}
Everything works fine. However, the speed is very slow for now.
How to investigate what is a bottleneck for it?
What could be the reason for such slow startup?
Spring Boot has out-of-the-box support for embedded MongoDB. Also the embedmongo-spring seems dated as it hasn't been touched in 3 years.
Use the out-of-the-box support for embedded MongoDB instead of trying to wrap something else around it.
NOTE: You could also remove the <version> from the flapdoodle dependency as Spring Boot has dependency management for it as well.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
These dependencies should be all you need.
I had exactly the same issue, but I'm not using Spring Boot. I found out that the issue in my case is this line (embedded mongo uses that):
InetAddress ret = InetAddress.getLocalHost();
And this is the fix
InetAddress.getLocalHost() slow to run (30+ seconds)

Why hibernate doesn't create table and schema

I am using spring-boot and postgreSQL to develop basic restful service. I try to create table by using JPA, here is the application.properties file
# Disable feature detection by this undocumented parameter. Check the org.hibernate.engine.jdbc.internal.JdbcServiceImpl.configure method for more details.
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
#Default port set
#PostrgreSQL connection
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=myuser
spring.datasource.password=123456789
spring.jpa.generate-ddl=true
spring.jpa.show-sql = true
#create/create-drop/update/
spring.jpa.hibernate.ddl-auto = create
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
here is the entity
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "User", schema = "public")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private Long id;
#Column(name = "USERNAME")
String userName;
#Column(name = "USERSURNAME")
String userSurName;
#Column(name = "USERJOB")
String userJob;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSurName() {
return userSurName;
}
public void setUserSurName(String userSurName) {
this.userSurName = userSurName;
}
public String getUserJob() {
return userJob;
}
public void setUserJob(String userJob) {
this.userJob = userJob;
}
}
when I run the application, I am expecting User table must be created. But there is no table or schema.
I can not find any error.
here is the log.
2018-07-25 11:31:11.139 INFO 10264 --- [ restartedMain] com.app.service.DemoApplication : Starting DemoApplication on S00 with PID 10264 (D:\JAVA\WEBZEROWORKSPACE\webzeroproject\target\classes started by s00 in D:\JAVA\WEBZEROWORKSPACE\webzeroproject)
2018-07-25 11:31:11.140 INFO 10264 --- [ restartedMain] com.app.service.DemoApplication : No active profile set, falling back to default profiles: default
2018-07-25 11:31:11.144 INFO 10264 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#477d52e0: startup date [Wed Jul 25 11:31:11 EET 2018]; root of context hierarchy
2018-07-25 11:31:11.413 INFO 10264 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$8dd8984d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-07-25 11:31:11.491 INFO 10264 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-07-25 11:31:11.491 INFO 10264 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-07-25 11:31:11.491 INFO 10264 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-07-25 11:31:11.517 INFO 10264 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-07-25 11:31:11.518 INFO 10264 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 374 ms
2018-07-25 11:31:11.542 INFO 10264 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-07-25 11:31:11.542 INFO 10264 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-07-25 11:31:11.542 INFO 10264 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-07-25 11:31:11.542 INFO 10264 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-07-25 11:31:11.542 INFO 10264 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-07-25 11:31:11.576 INFO 10264 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Starting...
2018-07-25 11:31:11.618 INFO 10264 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Start completed.
2018-07-25 11:31:11.618 INFO 10264 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-07-25 11:31:11.618 INFO 10264 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-07-25 11:31:11.618 INFO 10264 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2018-07-25 11:31:11.618 INFO 10264 --- [ restartedMain] o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000422: Disabling contextual LOB creation as connection was null
2018-07-25 11:31:11.618 INFO 10264 --- [ restartedMain] org.hibernate.type.BasicTypeRegistry : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#1cb89f80
2018-07-25 11:31:11.680 INFO 10264 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-07-25 11:31:11.700 INFO 10264 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-25 11:31:11.762 INFO 10264 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#477d52e0: startup date [Wed Jul 25 11:31:11 EET 2018]; root of context hierarchy
2018-07-25 11:31:11.784 WARN 10264 --- [ restartedMain] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2018-07-25 11:31:11.785 INFO 10264 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{user}],methods=[DELETE]}" onto public void com.sihab.service.CommonRestController.deleteUser(java.lang.Long)
2018-07-25 11:31:11.785 INFO 10264 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{user}],methods=[GET]}" onto public com.sihab.model.User com.sihab.service.CommonRestController.getUser(java.lang.Long)
2018-07-25 11:31:11.785 INFO 10264 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-07-25 11:31:11.785 INFO 10264 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-07-25 11:31:11.801 INFO 10264 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-25 11:31:11.801 INFO 10264 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-25 11:31:11.840 WARN 10264 --- [ restartedMain] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2018-07-25 11:31:11.918 INFO 10264 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2018-07-25 11:31:11.951 INFO 10264 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-07-25 11:31:11.952 INFO 10264 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-07-25 11:31:11.958 INFO 10264 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-07-25 11:31:11.971 INFO 10264 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-07-25 11:31:11.972 INFO 10264 --- [ restartedMain] com.sihab.service.DemoApplication : Started DemoApplication in 0.856 seconds (JVM running for 1978.331)
2018-07-25 11:31:11.979 INFO 10264 --- [ restartedMain] .ConditionEvaluationDeltaLoggingListener : Condition evaluation unchanged
Edit: Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>webzero</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<description>web project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<name>webtest</name>
</project>
I tried to reproduce the same issue but couldn't, here are my steps:
Go to https://start.spring.io and create a demo project with JPA ,
Postgres Dependencies with 1.5.14 version of Spring boot.
Add User Class to the same package where the #SpringBootApplication
class has been placed.
Updated Application.properties with the same properties(Updated DB
details).
Here are the logs hibernate specific:
org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl
schema export
Hibernate: drop table if exists public.user cascade
Hibernate: drop sequence hibernate_sequence
Hibernate: create table public.user (id int8 not null, userjob
varchar(255), username varchar(255), usersurname varchar(255),
primary key (id))
Hibernate: create sequence hibernate_sequence start 1 increment 1
My Pom.xml is
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.14.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
You can post your pom.xml if you still face issues after the above instructions.
If you want to place the entity classes in a different package from where your SpringBoot Application is placed , you can use do that by providing path of your entities by annotating your SpringBootApplication with
#EntityScan( basePackages = {"package-name"} )
More info at https://dzone.com/articles/spring-boot-entity-scan