Why hibernate doesn't create table and schema - postgresql

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

Related

SpringBoot Application Context error: : Kotlin, Gradle,Database, Docker Postgresql

I wanted to setup a connection between my postgresql database, which is inside a docker container and my Project.
The Docker an everything is set up via a docker compose file which looks like this:
version: '3.8'
services:
db:
container_name: postgres_container
image: postgres
restart: always
environment:
POSTGRES_DB: postgres_db
POSTGRES_USER: admin
POSTGRES_PASSWORD: secret
PGDATA: /var/lib/postgresql/data
ports:
- "5432:5432"
volumes:
- db-data:/var/lib/postgresql/data
pgadmin:
container_name: pgadmin4_container
image: dpage/pgadmin4:5.5
restart: always
environment:
PGADMIN_DEFAULT_EMAIL: admin#admin.com
PGADMIN_DEFAULT_PASSWORD: secret
PGADMIN_LISTEN_PORT: 80
ports:
- "8080:80"
volumes:
- pgadmin-data:/var/lib/pgadmin
links:
- "db:pgsql-server"
volumes:
db-data:
pgadmin-data:
My Project is supposed to be written in Kotlin an I have set up Spring Boot with the initializer, which looked like following:
enter image description here
I have added the following into the application properties file to get a connection to the database.
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres_db
spring.datasource.username=admin
spring.datasource.password=secret
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
This is my main file:
package com.nosiaj.nstudycloud
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
#SpringBootApplication
class NstudycloudApplication
fun main(args: Array<String>) {
runApplication<NstudycloudApplication>(*args)
}
And I wanted to create a table via code
package com.nosiaj.nstudycloud.entity
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
#Table(name="customer")
#Entity
class Customer {
#Id
private var uId: String = TODO("initialize me")
private val firstName: String
private val lastName: String
private val email: String
private val phone: String
private val IBAN: String
}
This is my build.gradle.kts file:
plugins {
id("org.springframework.boot") version "2.7.2"
id("io.spring.dependency-management") version "1.0.12.RELEASE"
kotlin("jvm") version "1.6.21"
kotlin("plugin.spring") version "1.6.21"
kotlin("plugin.jpa") version "1.6.21"
}
group = "com.nosiaj"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_17
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
runtimeOnly("org.postgresql:postgresql")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "17"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
Now when I start the application it connects to the database and creates the table, but I still get Error and the server stops. This is the Output:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.2)
2022-08-07 16:54:22.736 INFO 55209 --- [ main] c.n.n.NstudycloudApplicationKt : Starting NstudycloudApplicationKt using Java 17.0.4 on simba-desktop with PID 55209 (/home/simba/Dokumente/Project/nstudycloud/nstudycloud/build/classes/kotlin/main started by simba in /home/simba/Dokumente/Project/nstudycloud/nstudycloud)
2022-08-07 16:54:22.739 INFO 55209 --- [ main] c.n.n.NstudycloudApplicationKt : No active profile set, falling back to 1 default profile: "default"
2022-08-07 16:54:23.342 INFO 55209 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-08-07 16:54:23.359 INFO 55209 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 3 ms. Found 0 JPA repository interfaces.
2022-08-07 16:54:23.743 INFO 55209 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-08-07 16:54:23.750 INFO 55209 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-08-07 16:54:23.751 INFO 55209 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-08-07 16:54:23.812 INFO 55209 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-08-07 16:54:23.812 INFO 55209 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1026 ms
2022-08-07 16:54:23.949 INFO 55209 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-08-07 16:54:23.991 INFO 55209 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.10.Final
2022-08-07 16:54:24.110 INFO 55209 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-08-07 16:54:24.182 INFO 55209 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-08-07 16:54:24.286 INFO 55209 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-08-07 16:54:24.298 INFO 55209 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2022-08-07 16:54:24.594 INFO 55209 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-08-07 16:54:24.602 INFO 55209 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-08-07 16:54:24.635 WARN 55209 --- [ main] 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
2022-08-07 16:54:24.928 WARN 55209 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'webServerStartStop'; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat server
2022-08-07 16:54:24.930 INFO 55209 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-08-07 16:54:24.932 INFO 55209 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2022-08-07 16:54:24.938 INFO 55209 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2022-08-07 16:54:24.943 INFO 55209 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-08-07 16:54:24.955 INFO 55209 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-08-07 16:54:24.975 ERROR 55209 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.context.ApplicationContextException: Failed to start bean 'webServerStartStop'; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat server
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.22.jar:5.3.22]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.22.jar:5.3.22]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.22.jar:5.3.22]
at java.base/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na]
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.22.jar:5.3.22]
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.22.jar:5.3.22]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.22.jar:5.3.22]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.22.jar:5.3.22]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.2.jar:2.7.2]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.2.jar:2.7.2]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.2.jar:2.7.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.2.jar:2.7.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.2.jar:2.7.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.2.jar:2.7.2]
at com.nosiaj.nstudycloud.NstudycloudApplicationKt.main(NstudycloudApplication.kt:13) ~[main/:na]
Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat server
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.start(TomcatWebServer.java:229) ~[spring-boot-2.7.2.jar:2.7.2]
at org.springframework.boot.web.servlet.context.WebServerStartStopLifecycle.start(WebServerStartStopLifecycle.java:43) ~[spring-boot-2.7.2.jar:2.7.2]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.22.jar:5.3.22]
... 14 common frames omitted
Caused by: java.lang.IllegalArgumentException: standardService.connector.startFailed
at org.apache.catalina.core.StandardService.addConnector(StandardService.java:238) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.addPreviouslyRemovedConnectors(TomcatWebServer.java:282) ~[spring-boot-2.7.2.jar:2.7.2]
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.start(TomcatWebServer.java:213) ~[spring-boot-2.7.2.jar:2.7.2]
... 16 common frames omitted
Caused by: org.apache.catalina.LifecycleException: Protocol handler start failed
at org.apache.catalina.connector.Connector.startInternal(Connector.java:1077) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.StandardService.addConnector(StandardService.java:234) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
... 18 common frames omitted
Caused by: java.net.BindException: Die Adresse wird bereits verwendet
at java.base/sun.nio.ch.Net.bind0(Native Method) ~[na:na]
at java.base/sun.nio.ch.Net.bind(Net.java:555) ~[na:na]
at java.base/sun.nio.ch.ServerSocketChannelImpl.netBind(ServerSocketChannelImpl.java:337) ~[na:na]
at java.base/sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:294) ~[na:na]
at org.apache.tomcat.util.net.NioEndpoint.initServerSocket(NioEndpoint.java:275) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:230) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.net.AbstractEndpoint.bindWithCleanup(AbstractEndpoint.java:1227) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:1313) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:614) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.connector.Connector.startInternal(Connector.java:1074) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
... 20 common frames omitted
Process finished with exit code 1
So why does this Error appear? And how can I solve it ? I don't know what I am doing wrong, if someone could help me, that would be really great !!
Thanks a lot !!
It means another process is running on same port, so you have to kill it.
First, list which app using which that port and get it's pid
lsof -i:8080
Then kill it with
kill <pid>

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?

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)

Spring cloude: Zuul & consul

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

Spring Batch - the batch works in Eclipse but not as a JAR - without explicit DEBUG log

I am new to Spring. My batch works in Eclipse using Spring Boot.
public class Main {
public static void main(String [] args) {
System.exit(SpringApplication.exit(SpringApplication.run(BatchConfiguration.class, args)));
}
}
Here are the Eclipse's logs.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.1.4.RELEASE)
2014-08-08 12:01:09.714 INFO 292 --- [ main] f.i.a.fczeuj.springbatch.Main : Starting Main on W100023928 with PID 292 (started by Me in D:\Eclipse_workspace\SpringBatchJavaConfig)
2014-08-08 12:01:09.776 INFO 292 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#714ae2c1: startup date [Fri Aug 08 12:01:09 CEST 2014]; root of context hierarchy
2014-08-08 12:01:10.494 INFO 292 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'org.springframework.boot.autoconfigure.AutoConfigurationPackages': replacing [Generic bean: class [org.springframework.boot.autoconfigure.AutoConfigurationPackages$BasePackages]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.springframework.boot.autoconfigure.AutoConfigurationPackages$BasePackages]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2014-08-08 12:01:10.979 WARN 292 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean Javadoc for complete details
2014-08-08 12:01:10.994 WARN 292 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean Javadoc for complete details
2014-08-08 12:01:11.166 INFO 292 --- [ main] o.s.j.d.DriverManagerDataSource : Loaded JDBC driver: org.postgresql.Driver
sql=insert into schema_batch_01.table_batch_donnees_massives values (:num_ligne,(((extract('epoch' from statement_timestamp())*1000)::bigint)-1407492071384)/1000,:prenom, :nom, :rue, :ville, :etat)
2014-08-08 12:01:11.618 INFO 292 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [org/springframework/batch/core/schema-postgresql.sql]
2014-08-08 12:01:11.619 INFO 292 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [org/springframework/batch/core/schema-postgresql.sql] in 1 ms.
2014-08-08 12:01:11.822 INFO 292 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2014-08-08 12:01:11.838 INFO 292 --- [ main] o.s.b.a.b.JobLauncherCommandLineRunner : Running default command line with: []
2014-08-08 12:01:11.884 INFO 292 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: POSTGRES
2014-08-08 12:01:12.025 INFO 292 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2014-08-08 12:01:12.493 INFO 292 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{run.id=28}]
2014-08-08 12:01:12.664 INFO 292 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [taskletTruncate]
truncateDonnees DataSource=
org.springframework.jdbc.datasource.DriverManagerDataSource#7e913c56
Username=
role_cnx_batch_seminaire_dev
2014-08-08 12:01:13.102 INFO 292 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [stepInserts]
2014-08-08 12:01:18.079 INFO 292 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{run.id=28}] and the following status: [COMPLETED]
2014-08-08 12:01:18.079 INFO 292 --- [ main] f.i.a.fczeuj.springbatch.Main : Started Main in 8.677 seconds (JVM running for 9.239)
2014-08-08 12:01:18.079 INFO 292 --- [ main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#714ae2c1: startup date [Fri Aug 08 12:01:09 CEST 2014]; root of context hierarchy
2014-08-08 12:01:18.079 INFO 292 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
So I have built a JAR with maven dependencies and main class in the MANIFEST and run the JAR
java -jar myArchive.jar
But the JAR does nothing, without ERRORS in the DOS logs.
2014-08-08 12:10:47.125 DEBUG --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'batchConfiguration'
sql=insert into schema_batch_01.table_batch_donnees_massives values (:num_ligne,(((extract('epoch' from statement_timestamp())*1000)::bigint)-1407492647125)/1000,:prenom, :nom
, :rue, :ville, :etat)
2014-08-08 12:10:47.141 DEBUG --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Eagerly caching bean 'writer' to allow for resolving potential circular refere
nces
2014-08-08 12:10:47.141 DEBUG --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Invoking afterPropertiesSet() on bean with name 'writer'
2014-08-08 12:10:47.141 DEBUG --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Finished creating instance of bean 'writer'
2014-08-08 12:10:47.141 DEBUG --- [ main] s.c.a.AnnotationConfigApplicationContext : Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using defa
ult [org.springframework.context.support.DefaultLifecycleProcessor#4dc1c92b]
2014-08-08 12:10:47.141 DEBUG --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'lifecycleProcessor'
2014-08-08 12:10:47.141 DEBUG --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Searching for key 'spring.liveBeansView.mbeanDomain' in [systemProperties]
2014-08-08 12:10:47.141 DEBUG --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Searching for key 'spring.liveBeansView.mbeanDomain' in [systemEnvironment]
2014-08-08 12:10:47.141 DEBUG --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Searching for key 'spring.liveBeansView.mbeanDomain' in [class path resource [
spring.batch.context.properties]]
2014-08-08 12:10:47.141 DEBUG --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Could not find key 'spring.liveBeansView.mbeanDomain' in any property source.
Returning [null]
2014-08-08 12:10:47.157 INFO --- [ main] f.i.a.fczeuj.springbatch.Main : Started Main in 0.952 seconds (JVM running for 1.264)
2014-08-08 12:10:47.157 INFO --- [ main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationCont
ext#356f144c: startup date [Fri Aug 08 12:10:46 CEST 2014]; root of context hierarchy
2014-08-08 12:10:47.157 DEBUG --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'lifecycleProcessor'
2014-08-08 12:10:47.157 DEBUG --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Destroying singletons in org.springframework.beans.factory.support.DefaultList
ableBeanFactory#11e7c5cb: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowi
redAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,batc
hConfiguration,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcess
or.enhancedConfigurationProcessor,org.springframework.batch.core.configuration.annotation.ScopeConfiguration,stepScope,jobScope,org.springframework.batch.core.configuration.an
notation.SimpleBatchConfiguration,jobRepository,jobLauncher,jobRegistry,jobExplorer,transactionManager,jobBuilders,stepBuilders,fr.insee.architecture.fczeuj.springbatch.Contex
tWithProperties,dataSource,nbIteration,org.springframework.boot.autoconfigure.AutoConfigurationPackages,taskletTruncate,reader,processor,writer,job,stepInserts]; root of facto
ry hierarchy
2014-08-08 12:10:47.157 DEBUG --- [ main] o.s.b.f.support.DisposableBeanAdapter : Invoking destroy() on bean with name 'batchConfiguration'
2014-08-08 12:10:47.157 DEBUG --- [ main] o.s.b.f.support.DisposableBeanAdapter : Invoking destroy() on bean with name 'org.springframework.batch.core.configura
tion.annotation.SimpleBatchConfiguration'
2014-08-08 12:10:47.157 DEBUG --- [ main] o.s.b.f.support.DisposableBeanAdapter : Invoking destroy() on bean with name 'fr.architecture.springbatch
.ContextWithProperties'
2014-08-08 12:10:47.157 DEBUG --- [ main] o.s.b.f.support.DisposableBeanAdapter : Invoking destroy() on bean with name 'org.springframework.batch.core.configura
tion.annotation.ScopeConfiguration'
the missing logs between the JAR and Eclipse is just after the log line :
sql=insert into schema_batch_01.table_batch_donnees_massives values (:num_ligne,(((extract('epoch' from statement_timestamp())*1000)::bigint)-1407492647125)/1000,:prenom, :nom
, :rue, :ville, :etat)
Do you have an idea why my JAR aborts without running the Job ? Thank you.
Are you building with maven? If so, using the maven-assembly-plugin does not result in a jar file that runs the batch job, you'll need to use the spring-boot-maven-plugin like this:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.1.4.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>your.MainClass</mainClass>
</configuration>
</plugin>
</plugins>
</build>
You can then use the standard "mvn clean package" command to get an executable jar that contains all necessary dependencies and the correct manifest file.