spring boot docker crashes a whole image on live reload - java

The problem is when spring boot app gets triggered by live reload. Then it usually crashes a whole docker image. it's not on every live reload happens, but it happens very often.
docker-compose.yml
version: "3.7"
services:
app:
image: youtube-spring-boot-image
ports:
- "8080:8080"
depends_on:
- postgres
restart: always
postgres:
image: postgres:latest
volumes:
- postgres-data:/var/lib/postgresql/data
ports:
- "5432:5432"
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
- POSTGRES_DB=posts
restart: unless-stopped
volumes:
postgres-data:
application.yml
spring:
devtools:
restart:
poll-interval: 2s
quiet-period: 1s
data:
web:
pageable:
one-indexed-parameters: true
max-page-size: 50
profiles:
active: dev
---
spring:
config:
activate:
on-profile: dev
devtools:
remote:
secret: "mysecret"
datasource:
username: postgres
url: jdbc:postgresql://postgres:5432/posts
password: postgres
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
format_sql: 'true'
hibernate:
ddl-auto: update
show-sql: 'true'
mvc:
throw-exception-if-no-handler-found: 'true'
ChannelController.java
package com.project.youtube.channel;
import com.project.youtube.channel.dto.body.CreateChannelDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.UUID;
#RestController
#RequestMapping("/api/v1/channels")
public class ChannelController {
#Autowired
ChannelServiceInterface channelService;
#PostMapping
Channel createChannel(#Valid #RequestBody CreateChannelDTO channel){
return channelService.saveChannel(channel);
}
#GetMapping("/findById/{id}")
Channel findById(#PathVariable UUID id){
return channelService.findById(id).orElseThrow();
}
#GetMapping("/findByName/{name}")
Channel findByName(#PathVariable String name){
return channelService.findByName(name).orElseThrow();
}
}
ChannelService.java
package com.project.youtube.channel;
import com.project.youtube.channel.dto.body.CreateChannelDTO;
import com.project.youtube.common.exception.BadRequestException;
import com.project.youtube.user.User;
import com.project.youtube.user.UserServiceInterface;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.UUID;
#Service
public class ChannelService implements ChannelServiceInterface {
#Autowired
ChannelRepository channelRepository;
#Autowired
ModelMapper modelMapper;
#Autowired
UserServiceInterface userService;
#Override
public Page<Channel> findAll(Pageable pageable) {
return null;
}
#Override
public Channel saveChannel(CreateChannelDTO channel) {
Channel channelEntity = modelMapper.map(channel, Channel.class);
User user = userService.findById(channel.getUser()).orElseThrow();
System.out.println(user);
if(user.getChannel() != null){
throw new BadRequestException("User already has a channel");
}
channelEntity.setUser(user);
return channelRepository.save(channelEntity);
}
#Override
public Optional<Channel> findById(UUID id) {
return channelRepository.findById(id);
}
#Override
public Optional<Channel> findByName(String name) {
return channelRepository.findByName(name);
}
}
error
2022-10-22 15:07:20.441 INFO 1 --- [ restartedMain] com.project.youtube.YoutubeApplication : Starting YoutubeApplication v0.0.1-SNAPSHOT using Java 17.0.4.1 on 369da96882ed with PID 1 (/workspace/BOOT-INF/classes started by cnb in /workspace)
2022-10-22 15:07:20.441 INFO 1 --- [ restartedMain] com.project.youtube.YoutubeApplication : The following 1 profile is active: "dev"
2022-10-22 15:07:20.568 INFO 1 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-10-22 15:07:20.577 INFO 1 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 8 ms. Found 4 JPA repository interfaces.
2022-10-22 15:07:20.620 INFO 1 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-10-22 15:07:20.621 INFO 1 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-10-22 15:07:20.621 INFO 1 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-10-22 15:07:20.626 INFO 1 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-10-22 15:07:20.626 INFO 1 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 183 ms
2022-10-22 15:07:20.649 WARN 1 --- [ restartedMain] .s.b.d.a.RemoteDevToolsAutoConfiguration : Listening for remote restart updates on /.~~spring-boot!~/restart
2022-10-22 15:07:20.660 INFO 1 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-10-22 15:07:20.662 INFO 1 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-5 - Starting...
2022-10-22 15:07:20.670 INFO 1 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-5 - Start completed.
2022-10-22 15:07:20.671 INFO 1 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2022-10-22 15:07:20.751 INFO 1 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-10-22 15:07:20.751 INFO 1 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-10-22 15:07:20.756 WARN 1 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.f
actory.UnsatisfiedDependencyException: Error creating bean with name 'channelController': Unsatisfied dependency expressed through field 'channelService'; nested exception is org.springframework.beans.facto
ry.NoSuchBeanDefinitionException: No qualifying bean of type 'com.project.youtube.channel.ChannelServiceInterface' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2022-10-22 15:07:20.756 INFO 1 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-10-22 15:07:20.757 INFO 1 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-5 - Shutdown initiated...
2022-10-22 15:07:20.758 INFO 1 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-5 - Shutdown completed.
2022-10-22 15:07:20.758 INFO 1 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-10-22 15:07:20.764 INFO 1 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-10-22 15:07:20.780 ERROR 1 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field channelService in com.project.youtube.channel.ChannelController required a bean of type 'com.project.youtube.channel.ChannelServiceInterface' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.project.youtube.channel.ChannelServiceInterface' in your configuration.
Native Memory Tracking:
Total: reserved=6967925842, committed=410233938
- Java Heap (reserved=6144655360, committed=155189248)
(mmap: reserved=6144655360, committed=155189248)
- Class (reserved=98438868, committed=12259028)
(classes #16438)
( instance classes #15272, array classes #1166)
(malloc=1969876 #37911)
(mmap: reserved=96468992, committed=10289152)
( Metadata: )
( reserved=67108864, committed=63832064)
( used=63492728)
( waste=339336 =0.53%)
( Class space:)
( reserved=96468992, committed=10289152)
( used=9920144)
( waste=369008 =3.59%)
- Thread (reserved=28445208, committed=1350168)
(thread #28)
(stack: reserved=28364800, committed=1269760)
(malloc=45944 #196)
(arena=34464 #60)
- Code (reserved=255452840, committed=27645608)
(malloc=1820328 #9753)
(mmap: reserved=253632512, committed=25825280)
- GC (reserved=284467544, committed=62202200)
(malloc=22499672 #9236)
(mmap: reserved=261967872, committed=39702528)
- Compiler (reserved=44841728, committed=44841728)
(malloc=47848 #1198)
(arena=44793880 #27)
- JVMCI (reserved=104, committed=104)
(malloc=104 #7)
- Internal (reserved=452902, committed=452902)
(malloc=416038 #11608)
(mmap: reserved=36864, committed=36864)
- Symbol (reserved=16537712, committed=16537712)
(malloc=15678152 #395104)
(arena=859560 #1)
- Native Memory Tracking (reserved=7534776, committed=7534776)
(malloc=7288 #101)
(tracking overhead=7527488)
- Shared class space (reserved=12582912, committed=10981376)
(mmap: reserved=12582912, committed=10981376)
- Arena Chunk (reserved=6492528, committed=6492528)
(malloc=6492528)
- Tracing (reserved=33121, committed=33121)
(malloc=393 #10)
(arena=32728 #1)
If I wanna start my app first I run ./mvnw spring-boot:build-image -fn to create spring boot image and then docker-compose up. It starts perfectly fine, it crashes only when live reload is triggered. Also I have created run configuration in intellij (without it live reload is not working).
So if anyone knows how to deal with it, please help, cause this became very frustrating. I actually do not know what is wrong here. This is the only docker setup, that I able to find, that works with live reload, if someone knows better docker setup, that works with live reload please share with me.
github https://github.com/EivydasV/spring-youtube

Related

Java Spring error with #Service #Controller #Repository: Error creating bean

please, I need some help, I've been stuck with this error 2 days.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'adsController': Unsatisfied dependency expressed through field 'shortUrlService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'shortUrlServiceImpl': Unsatisfied dependency expressed through field 'shortUrlRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shortUrlRepository' defined in com.codepressed.urlShortener.dao.ShortUrlRepository defined in #EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property desc found for type LocalDateTime! Traversed path: ShortUrl.creationDate.
Error display
This is my code:
Service class
#Service
public class AdvertisementServiceImpl implements AdvertisementService{
#Autowired
AdvertisementRepository advertisementRepository;
#Autowired
private MongoUtilsService mongoUtilsService;
#Override
public Advertisement save(Advertisement advertisement) {
advertisement.set_id(mongoUtilsService.getNextValue("AD"));
return advertisementRepository.insert(advertisement);
}
#Override
public void removeAd(Advertisement advertisement) {
advertisementRepository.delete(advertisement);
}
#Override
public Advertisement randomAd() {
List<Advertisement> allAds = advertisementRepository.findAll();
Random random = new Random();
return allAds.get(random.nextInt(allAds.size()-1));
}
}
My repository
#RepositoryRestResource
public interface AdvertisementRepository extends MongoRepository<Advertisement,Long> {
}
Controller class
#Controller
#RequestMapping("/ad")
public class AdsController {
#Autowired
AdvertisementService advertisementService;
#Autowired
ShortUrlService shortUrlService;
#GetMapping(value="/{id}")
public String getRandomAd(#PathVariable Long id, Model model){
model.addAttribute("ad", advertisementService.randomAd());
String url;
if (shortUrlService.findUrlById(id) != null){
url = shortUrlService.findUrlById(id);
}else if (shortUrlService.findUrlByCustom(String.valueOf(id)) != null){
url = shortUrlService.findUrlByCustom(String.valueOf(id));
}else {
url = "/error404.html";
}
model.addAttribute("url", url);
return "go";
}
I would like to use the ServiceImpl and Service but I don't know why wouldn't I be able to autowire them.
Additionaly, I have on my Config Class the following annotation:
#ComponentScan({"com.codepressed.urlShortener", "com.codepressed.urlShortener.dao",
"com.codepressed.urlShortener.service", "com.codepressed.urlShortener.controller"})
but doesn't seem to be enough...
please, any help is appreciated, I can't see the error or I don't understand it.
GITHUB REPO: https://github.com/codepressed/Jurly/tree/master/src/main/java/com/codepressed/urlShortener
I just cloned your code, on github.
I found that your method naming does not conform to the Spring-Data JPA specification.
Rename ShortUrlRepository method:
List<ShortUrl> findFirst10ByCreationDateDesc();
to:
List<ShortUrl> findFirst10ByOrderByCreationDateDesc();
When this problem is solved, run the application,console output:
No session repository could be auto-configured, check your configuration
So I created a mongo http session config:
package com.codepressed.urlShortener.config;
import org.springframework.context.annotation.Bean;
import org.springframework.session.data.mongo.JdkMongoSessionConverter;
import org.springframework.session.data.mongo.config.annotation.web.http.EnableMongoHttpSession;
import java.time.Duration;
#EnableMongoHttpSession
public class HttpSessionConfig {
#Bean
public JdkMongoSessionConverter jdkMongoSessionConverter() {
return new JdkMongoSessionConverter(Duration.ofMinutes(30));
}
}
Then I run the application again,No exception output!
2021-06-18 00:06:49.844 INFO 13960 --- [ main] c.c.u.UrlShortenerApplication : Starting UrlShortenerApplication using Java 11.0.10 on Mashiros-iMac.lan with PID 13960 (/Users/rat/IdeaProjects/Jurly/target/classes started by rat in /Users/rat/IdeaProjects/Jurly)
2021-06-18 00:06:49.850 INFO 13960 --- [ main] c.c.u.UrlShortenerApplication : No active profile set, falling back to default profiles: default
2021-06-18 00:06:50.295 INFO 13960 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2021-06-18 00:06:50.329 INFO 13960 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 32 ms. Found 2 MongoDB repository interfaces.
2021-06-18 00:06:50.667 INFO 13960 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-06-18 00:06:50.674 INFO 13960 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-06-18 00:06:50.674 INFO 13960 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.45]
2021-06-18 00:06:50.717 INFO 13960 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-06-18 00:06:50.718 INFO 13960 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 833 ms
2021-06-18 00:06:50.838 INFO 13960 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2021-06-18 00:06:50.875 INFO 13960 --- [127.0.0.1:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:1}] to 127.0.0.1:27017
2021-06-18 00:06:50.875 INFO 13960 --- [127.0.0.1:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:2}] to 127.0.0.1:27017
2021-06-18 00:06:50.876 INFO 13960 --- [127.0.0.1:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=9, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=11069828}
2021-06-18 00:06:51.052 INFO 13960 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:3}] to 127.0.0.1:27017
2021-06-18 00:06:51.067 INFO 13960 --- [ main] o.s.s.d.m.AbstractMongoSessionConverter : Creating TTL index on field expireAt
2021-06-18 00:06:51.536 INFO 13960 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-06-18 00:06:51.600 INFO 13960 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2021-06-18 00:06:51.891 INFO 13960 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: 1c0d09bd-73cc-42aa-8f6a-df157db252fe
2021-06-18 00:06:52.022 INFO 13960 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#1e95f584, org.springframework.security.web.context.SecurityContextPersistenceFilter#1a336906, org.springframework.security.web.header.HeaderWriterFilter#39afe59f, org.springframework.security.web.csrf.CsrfFilter#3a3316b6, org.springframework.security.web.authentication.logout.LogoutFilter#57fce8b, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#1b4ba615, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#3a9c11fb, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#54997f67, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#18e8eb59, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#20f63ddc, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#24f177f5, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#bf4e48e, org.springframework.security.web.session.SessionManagementFilter#43756cb, org.springframework.security.web.access.ExceptionTranslationFilter#48ee3c2d, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#e6e5da4]
2021-06-18 00:06:52.105 INFO 13960 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-06-18 00:06:52.115 INFO 13960 --- [ main] c.c.u.UrlShortenerApplication : Started UrlShortenerApplication in 2.542 seconds (JVM running for 3.116)
I think you should refer to the following tutorials:
Spring Session with MongoDB
Sorting Query Results with Spring Data

#SpringBootApplication Annotation not finding beans in classpath

From my understanding using #SpringBootApplication is the equivalent of having #EnableAutoConfiguration and #ComponentScan. For this reason I can't understand why Spring isn't finding my annotations. As far as I'm aware the project structure is as it should be and everything is annotated properly. However when I visit the mapped endpoint http://localhost:8080/dashboard or http://localhost:8080/dashboard/, I see a 404 error.
I just created a new Spring Boot project using IntelliJ's built in Spring Initialiser, I selected Spring Web, and a few components for Postgres. Inside the project I can't find any additional .xml files for configuration. However, I did find:
DataSourceInitializerInvoker.java - which hasn't been edited
ConfigurationPropertiesAutoConfiguration.java - which hasn't been edited
Structure of my project is as follows:
com
+-abcde
+-appname
+-controllers
DashboardController.java
Application.java
Application.java:
package com.abcde.appname;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
DashboardController.java
package com.abcde.appname.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping("/dashboard")
public class DashboardController {
#Autowired
public DashboardController() {
}
#GetMapping
public ModelAndView renderDashboard() {
return new ModelAndView("dashboard/index");
}
}
Alongside these files I also have the following,
application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=user
spring.datasource.driver-class-name=org.postgresql.Driver
spring.main.banner-mode=off
build.gradle
plugins {
id 'org.springframework.boot' version '2.3.3.RELEASE'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
id 'java'
}
group = 'com.abcde'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '14'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.flywaydb:flyway-core'
runtimeOnly 'org.postgresql:postgresql'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
stacktrace
2020-09-09 23:24:46.053 INFO 57966 --- [ main] c.d.f.Application : Starting Application on OP-MacBook-Pro.local with PID 57966 (/Users/op/IdeaProjects/lalala/build/classes/java/main started by op in /Users/op/IdeaProjects/lalala)
2020-09-09 23:24:46.054 INFO 57966 --- [ main] c.d.f.Application : No active profile set, falling back to default profiles: default
2020-09-09 23:24:46.374 INFO 57966 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-09-09 23:24:46.388 INFO 57966 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10ms. Found 0 JPA repository interfaces.
2020-09-09 23:24:46.716 INFO 57966 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-09-09 23:24:46.720 INFO 57966 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-09-09 23:24:46.720 INFO 57966 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-09-09 23:24:46.775 INFO 57966 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-09-09 23:24:46.775 INFO 57966 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 700 ms
2020-09-09 23:24:46.832 INFO 57966 --- [ main] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 6.4.4 by Redgate
2020-09-09 23:24:46.835 INFO 57966 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-09-09 23:24:46.872 INFO 57966 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-09-09 23:24:46.879 INFO 57966 --- [ main] o.f.c.internal.database.DatabaseFactory : Database: jdbc:postgresql://localhost:5432/postgres (PostgreSQL 12.3)
2020-09-09 23:24:46.901 INFO 57966 --- [ main] o.f.core.internal.command.DbValidate : Successfully validated 1 migration (execution time 00:00.011s)
2020-09-09 23:24:46.905 INFO 57966 --- [ main] o.f.core.internal.command.DbMigrate : Current version of schema "public": 10
2020-09-09 23:24:46.905 INFO 57966 --- [ main] o.f.core.internal.command.DbMigrate : Schema "public" is up to date. No migration necessary.
2020-09-09 23:24:46.960 INFO 57966 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-09-09 23:24:46.985 INFO 57966 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-09-09 23:24:47.000 WARN 57966 --- [ 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
2020-09-09 23:24:47.010 INFO 57966 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.20.Final
2020-09-09 23:24:47.070 INFO 57966 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-09-09 23:24:47.122 INFO 57966 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
2020-09-09 23:24:47.253 INFO 57966 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-09-09 23:24:47.257 INFO 57966 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-09-09 23:24:47.264 INFO 57966 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-09-09 23:24:47.265 INFO 57966 --- [ main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-09-09 23:24:47.266 INFO 57966 --- [ main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-09-09 23:24:47.273 INFO 57966 --- [ main] c.d.f.lalala : Started Application in 1.401 seconds (JVM running for 1.885)
2020-09-09 23:24:49.520 INFO 57966 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-09-09 23:24:49.520 INFO 57966 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-09-09 23:24:49.524 INFO 57966 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
Any insight into this problem would be much appreciated. Many thanks
It's probably successfully invoking the renderDashboard() and is not finding "dashboard/index". You can verify that by debugging and setting a breakpoint or adding a log/System.out println statement. Does your index file exist and is it setup correctly?

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure when trying to build spring boot docker image

I am trying to build my docker image for my spring boot application but keep encountering this error:
:: Spring Boot :: (v2.2.5.RELEASE)
2020-05-31 02:18:39.820 INFO 63 --- [ main] c.g.Apollo.ApolloApplicationTests : Starting ApolloApplicationTests on 4b284b60945e with PID 63 (started by root in /build)
2020-05-31 02:18:39.838 INFO 63 --- [ main] c.g.Apollo.ApolloApplicationTests : No active profile set, falling back to default profiles: default
2020-05-31 02:18:42.208 INFO 63 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-31 02:18:42.467 INFO 63 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 216ms. Found 3 JPA repository interfaces.
2020-05-31 02:18:44.902 INFO 63 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-31 02:18:46.575 ERROR 63 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:354) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:202) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:554) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.4.2.jar:na]
Terminal when successfully running in intellij:
:: Spring Boot :: (v2.2.5.RELEASE)
2020-05-31 01:04:39.322 INFO 19524 --- [ restartedMain] c.g.Apollo.ApolloApplication : Starting ApolloApplication on asd-PC with PID 19524 (C:\Projects\Apollo\target\classes started by asd in C:\Projects\Apollo)
2020-05-31 01:04:39.324 INFO 19524 --- [ restartedMain] c.g.Apollo.ApolloApplication : No active profile set, falling back to default profiles: default
2020-05-31 01:04:39.354 INFO 19524 --- [ restartedMain] o.s.b.devtools.restart.ChangeableUrls : The Class-Path manifest attribute in C:\Users\asd\.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:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.xml.bind-api-2.3.2.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/txw2-2.3.2.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/istack-commons-runtime-3.0.8.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/stax-ex-1.8.1.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/FastInfoset-1.2.16.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.activation-api-1.2.1.jar
2020-05-31 01:04:39.354 INFO 19524 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-05-31 01:04:39.354 INFO 19524 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-05-31 01:04:39.785 INFO 19524 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-31 01:04:39.846 INFO 19524 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 54ms. Found 3 JPA repository interfaces.
2020-05-31 01:04:40.214 INFO 19524 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-05-31 01:04:40.220 INFO 19524 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-05-31 01:04:40.221 INFO 19524 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-05-31 01:04:40.293 INFO 19524 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-05-31 01:04:40.293 INFO 19524 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 939 ms
2020-05-31 01:04:40.365 INFO 19524 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-31 01:04:40.702 INFO 19524 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-05-31 01:04:40.731 INFO 19524 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-31 01:04:40.800 INFO 19524 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-05-31 01:04:40.919 INFO 19524 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-31 01:04:41.006 INFO 19524 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2020-05-31 01:04:41.407 INFO 19524 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-31 01:04:41.413 INFO 19524 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-31 01:04:41.650 WARN 19524 --- [ 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-05-31 01:04:41.717 INFO 19524 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-31 01:04:41.967 INFO 19524 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-05-31 01:04:41.995 INFO 19524 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-05-31 01:04:41.997 INFO 19524 --- [ restartedMain] c.g.Apollo.ApolloApplication : Started ApolloApplication in 2.911 seconds (JVM running for 3.899)
My Dockerfile:
FROM maven:3.6.3-jdk-11-slim AS MAVEN_BUILD
COPY pom.xml /build/
COPY src /build/src/
WORKDIR /build/
RUN mvn package
FROM openjdk:11-jre-alpine
WORKDIR /app
COPY --from=MAVEN_BUILD /build/target/*.war /app/app.war
ENTRYPOINT ["java", "-jar", "app.war"]
My application.properties:
## GraphQL SPQR ##
server.port=8080
graphql.spqr.gui.enabled=true
graphql.spqr.http.endpoint=/graphql
graphql.spqr.ws.endpoint=/graphql
## Database Properties ##
spring.datasource.url=jdbc:mysql://localhost:3306/innodb
spring.datasource.username=root
spring.datasource.password=1234
My application works when I build and run the project in Intellij but not when I try and build my docker image. I am using MySQL and have just been connecting on localhost on port 3306.
The error message seems to indicate the issue is failing to connect to the database. From your settings, it appears that you are trying to connect to the DB using localhost:3306. That will not work when you are running the application in a container because docker creates its own network which is separate from you machine’s network. So, localhost in the container does not refer to your machine.
You need to instead setup a docker network that will allow your container to access the database in a specific IP address.
Here is an article with the specifics:
https://nickjanetakis.com/blog/docker-tip-35-connect-to-a-database-running-on-your-docker-host
Note that I have assumed from your post, that the DB is installed in your host machine. If it is not and the DB is running in its own container, the you need to create a docker network and attach both containers to that network.
I had the same issue and resolved it by changing localhost to the service name on which MySQL was running.
Below is my docker-compose and application.properties files
docker-compose.yml
version: '3.8'
services:
app:
container_name: tvms
build:
context: .
dockerfile: Dockerfile
tty: true
volumes:
- ../..:/workspaces:cached
ports:
- 8990:8990
networks:
- impaq
links:
- db:db
db:
image: percona:8.0
privileged: true
restart: always
container_name: standalone-mysql
environment:
MYSQL_ROOT_PASSWORD: ****
volumes:
- perconadata:/var/lib/mysql
ports:
- 3306:3306
networks:
- impaq
networks:
impaq:
volumes:
perconadata:
application.propeties
#datasource
spring.datasource.url=jdbc:mysql://db:3306/db_name
spring.datasource.username=root
spring.datasource.password=*****
For me below solution worked
change your datasource url from
This:
spring.datasource.url=jdbc:mysql://localhost:3306/innodb
To:
spring.datasource.url=jdbc:mysql://localhost:3306/innodb?useSSL=false

What is the correct jdbc for Spring boot for containerized postgressql

I have a Spring boot app that is containerized and published to the docker hub. I have this docker-copmse.yml:-
version: '3.1'
services:
postgres:
image: postgres
container_name: postgres
ports:
- "5432:5432"
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
- POSTGRES_DB=mydb
profile_back:
container_name: profile_back
image: madsum/profile_back
ports:
- "8080:8080"
depends_on:
- postgres
My spring boot application.propertiese:-
#spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.url=jdbc:postgresql://postgres:5432/mydb
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=true
I don't know what is the correct spring.datasource.url. I tried both jdbc:postgresql://localhost:5432/mydb and jdbc:postgresql://postgres:5432/mydb .Both give connection error. Btw, container runs perfectly. I can verify by it as docker exec -it --user postgres dbpostgresql sh . I can see the database created. What is the correct way to connect it?
Updated question:-
I am using flyway. Here is the exception now:-
ound 1 JPA repository interfaces.
2020-03-06 09:33:01.939 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-06 09:33:01.949 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-06 09:33:01.949 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-03-06 09:33:01.997 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-06 09:33:01.998 INFO 1 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1180 ms
2020-03-06 09:33:02.118 INFO 1 --- [ main] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 6.0.8 by Redgate
2020-03-06 09:33:02.124 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-03-06 09:33:02.127 WARN 1 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is java.lang.RuntimeException: Driver org.postgresql.Driver claims to not accept jdbcUrl, jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
2020-03-06 09:33:02.130 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-03-06 09:33:02.141 INFO 1 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-06 09:33:02.145 ERROR 1 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is java.lang.RuntimeException: Driver org.postgresql.Driver claims to not accept jdbcUrl, jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.4.RELEASE.jar!/:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.4.RELEASE.jar!/:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.4.RELEASE.jar!/:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.4.RELEASE.jar!/:5.2.4.RELEASE]
Carefully reading the exception, gives you a valuable hint:
Invocation of init method failed; nested exception is
java.lang.RuntimeException: Driver org.postgresql.Driver claims to not
accept jdbcUrl,
jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE 2020-03-06
So it seems your application tries to connect to an in-memory H2 database and not to PostgreSQL.
Do you maybe use different profiles for your application and forgot to set the production profile? Otherwise, you can get rid of the H2 dependency in your pom.xml/build.gradle if you don't need it
Try using 127.0.0.1 instead of localhost

autowiring an interface Error in Spring boot

I'm currently facing this problem in Spring Boot when it comes to wiring a repository interface to a service class.
here's my Item class
package com.ensa.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Item {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private float prix;
public Item(Long id,String name,float prix) {
this.id=id;
this.name=name;
this.prix=prix;
}
public Item() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrix() {
return prix;
}
public void setPrix(float prix) {
this.prix = prix;
}}
here's my repository Interface
package com.ensa.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.ensa.entity.Item;
#Repository
#Component
public interface ItemRepository extends JpaRepository<Item, Long> {
}
my Service class:
package com.ensa.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ensa.entity.Item;
import com.ensa.repository.ItemRepository;
#Service
#Transactional
public class ItemService {
#Autowired
private ItemRepository itemRepo ;
private List<Item> list = new ArrayList<Item>();
public ItemService() {
Item A= new Item(1L,"AAAA",2);
list.add(A);
//itemRepo.count();
}
public List<Item> getAllItems() { //Returning all Items
return list;
}
public Item getItemById(Long id) { //getting Item by Id
return null;
}
public void addItem(Item item) { //adding new item
list.add(item);
}
public void updateItem(Long id, Item item) { //updating an existing Item
itemRepo.save(item);
}
public void deleteItem(Long id) { //deleting Item by id
for (Item temp : list) {
if (temp.getId() == id) {
int i = list.indexOf(temp);
list.remove(i);
return;
}
}
}
}
I was working with a list to test out the REST api but once I added the repository I started getting this error
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE)
2020-03-05 10:19:41.426 INFO 468 --- [ main] com.ensa.app.SpringApp : Starting SpringApp on DESKTOP-FPSG9AG with PID 468 (C:\Users\perso\eclipse-workspace\springTest\target\classes started by perso in C:\Users\perso\eclipse-workspace\springTest)
2020-03-05 10:19:41.430 INFO 468 --- [ main] com.ensa.app.SpringApp : No active profile set, falling back to default profiles: default
2020-03-05 10:19:42.226 INFO 468 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2020-03-05 10:19:42.252 INFO 468 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 17ms. Found 0 repository interfaces.
2020-03-05 10:19:42.680 INFO 468 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d295b9fe] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-03-05 10:19:43.105 INFO 468 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-05 10:19:43.152 INFO 468 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-05 10:19:43.153 INFO 468 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.16]
2020-03-05 10:19:43.161 INFO 468 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk-13.0.1\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jdk-13.0.1/bin/server;C:/Program Files/Java/jdk-13.0.1/bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;c:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\;c:\Program Files\Microsoft SQL Server\110\Tools\Binn\;c:\Program Files\Microsoft SQL Server\110\DTS\Binn\;c:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\;c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\;c:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files\Java\jdk-13.0.1\bin;C:\Program Files\apache-maven-3.6.3\bin;;C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.3.3\bin;;C:\Users\perso\OneDrive\Bureau;;.]
2020-03-05 10:19:43.352 INFO 468 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-05 10:19:43.352 INFO 468 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1873 ms
2020-03-05 10:19:43.563 INFO 468 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-03-05 10:19:43.705 INFO 468 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-03-05 10:19:43.765 INFO 468 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2020-03-05 10:19:43.849 INFO 468 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final}
2020-03-05 10:19:43.851 INFO 468 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2020-03-05 10:19:44.022 INFO 468 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2020-03-05 10:19:44.190 INFO 468 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2020-03-05 10:19:44.538 INFO 468 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-03-05 10:19:44.584 WARN 468 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'itemController': Unsatisfied dependency expressed through field 'itemServ'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'itemService': Unsatisfied dependency expressed through field 'itemRepo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ensa.repository.ItemRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2020-03-05 10:19:44.584 INFO 468 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-03-05 10:19:44.589 INFO 468 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-03-05 10:19:44.602 INFO 468 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2020-03-05 10:19:44.603 INFO 468 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-03-05 10:19:44.619 INFO 468 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-05 10:19:44.781 ERROR 468 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field itemRepo in com.ensa.service.ItemService required a bean of type 'com.ensa.repository.ItemRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.ensa.repository.ItemRepository' in your configuration.
**
Any ideas on how to solve this problem?
You don't need to add #Repository or #Component on repository class. Remove those annotation from repository. Just use like
public interface ItemRepository extends JpaRepository<Item, Long> {
}
And try replacing itemRepo with itemRepository. So it will be like
#Autowired
private ItemRepository itemRepository;
use #EnableJPArepository("com.ensa.repository") in main class, it might work, if not try to use below line
#ComponentScan("com.ensa.repository") in your service class it might works
The #Repository is already a Stereotype annotation and so you don't need #Component with it.
You can remove the #Component annotation from your Repository.
#Repository
public interface ItemRepository extends JpaRepository<Item, Long> {
}
Also, It is not a good practice to use #Transactional on an entire class as it will slow down your code because database requires a lock for the time your entire code annotated with #Transactional executes.
While the others are right, and you could leave out #Component on #Repository, your actual error is that the #Bean could not be found.
#SpringBootApplication (the annotation on your main class) includes a #ComponentScan, which means Spring will scan all classes in the same package all subpackages for annotations/beans ( like #Component..or #Repository).
Make sure that your repository class is in the same package OR in a sub-package, not in a sibling-package. Otherwise, it cannot be found or you would have to modify your ComponentScan.
Then it should be found.

Categories

Resources