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.
Related
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
If I restart the project, the job I registered works well and the log is taken well.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.2)
2022-08-23 05:07:50.729 INFO 16360 --- [ restartedMain] c.capston.chatting.ChattingApplication : Starting ChattingApplication using Java 11.0.12 on DESKTOP-SHB62PK with PID 16360 (D:\chatting\chatting\build\classes\java\main started by user in D:\chatting\chatting)
2022-08-23 05:07:50.730 INFO 16360 --- [ restartedMain] c.capston.chatting.ChattingApplication : The following 4 profiles are active: "google", "naver", "kakao", "local"
2022-08-23 05:07:50.753 INFO 16360 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-08-23 05:07:50.753 INFO 16360 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-08-23 05:07:51.120 INFO 16360 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-08-23 05:07:51.152 INFO 16360 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 28 ms. Found 4 JPA repository interfaces.
2022-08-23 05:07:51.470 INFO 16360 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-08-23 05:07:51.474 INFO 16360 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-08-23 05:07:51.475 INFO 16360 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-08-23 05:07:51.547 INFO 16360 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-08-23 05:07:51.547 INFO 16360 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 794 ms
2022-08-23 05:07:51.595 INFO 16360 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-08-23 05:07:51.738 INFO 16360 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-08-23 05:07:51.793 INFO 16360 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-08-23 05:07:51.814 INFO 16360 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.10.Final
2022-08-23 05:07:51.889 INFO 16360 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-08-23 05:07:51.939 INFO 16360 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2022-08-23 05:07:52.204 INFO 16360 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-08-23 05:07:52.208 INFO 16360 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-08-23 05:07:52.636 INFO 16360 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter#62239b45, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#3596673e, org.springframework.security.web.context.SecurityContextPersistenceFilter#49f2b09c, org.springframework.security.web.header.HeaderWriterFilter#576fbb11, org.springframework.security.web.authentication.logout.LogoutFilter#2356ea3a, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#378ce71, org.springframework.security.web.session.ConcurrentSessionFilter#fac8000, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#704795de, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#41def366, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#36aed9df, org.springframework.security.web.session.SessionManagementFilter#280ea7a9, org.springframework.security.web.access.ExceptionTranslationFilter#32ddfe1, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#74600b37]
2022-08-23 05:07:52.641 INFO 16360 --- [ restartedMain] c.c.c.c.batch.InactiveMemberJobConfig : InactiveMemberJob execution
2022-08-23 05:07:52.641 INFO 16360 --- [ restartedMain] c.c.c.c.batch.InactiveMemberJobConfig : InactiveMemberStep execution
2022-08-23 05:07:52.642 INFO 16360 --- [ restartedMain] c.c.c.c.batch.InactiveMemberJobConfig : InactiveMemberReader execution
2022-08-23 05:07:52.660 DEBUG 16360 --- [ restartedMain] org.hibernate.SQL :
select
member0_.member_id as member_i1_3_,
member0_.created_date as created_2_3_,
member0_.update_date as update_d3_3_,
member0_.login_id as login_id4_3_,
member0_.login_pw as login_pw5_3_,
member0_.name as name6_3_,
member0_.role as role7_3_,
member0_.score as score8_3_,
member0_.status as status9_3_
from
member member0_
where
member0_.update_date<?
and member0_.status=?
2022-08-23 05:07:52.699 INFO 16360 --- [ restartedMain] c.c.c.c.batch.InactiveMemberJobConfig : test
2022-08-23 05:07:52.699 INFO 16360 --- [ restartedMain] c.c.c.c.batch.InactiveMemberJobConfig : InactiveMemberWriter execution
2022-08-23 05:07:52.826 WARN 16360 --- [ restartedMain] o.s.b.a.batch.JpaBatchConfigurer : JPA does not support custom isolation levels, so locks may not be taken when launching Jobs. To silence this warning, set 'spring.batch.jdbc.isolation-level-for-create' to 'default'.
2022-08-23 05:07:52.828 INFO 16360 --- [ restartedMain] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: MYSQL
2022-08-23 05:07:52.835 INFO 16360 --- [ restartedMain] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2022-08-23 05:07:52.912 INFO 16360 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2022-08-23 05:07:52.933 INFO 16360 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-08-23 05:07:52.934 INFO 16360 --- [ restartedMain] o.s.m.s.b.SimpleBrokerMessageHandler : Starting...
2022-08-23 05:07:52.935 INFO 16360 --- [ restartedMain] o.s.m.s.b.SimpleBrokerMessageHandler : BrokerAvailabilityEvent[available=true, SimpleBrokerMessageHandler [org.springframework.messaging.simp.broker.DefaultSubscriptionRegistry#25358374]]
2022-08-23 05:07:52.935 INFO 16360 --- [ restartedMain] o.s.m.s.b.SimpleBrokerMessageHandler : Started.
2022-08-23 05:07:52.941 INFO 16360 --- [ restartedMain] c.capston.chatting.ChattingApplication : Started ChattingApplication in 2.426 seconds (JVM running for 2.944)
2022-08-23 05:07:52.942 INFO 16360 --- [ restartedMain] o.s.b.a.b.JobLauncherApplicationRunner : Running default command line with: []
2022-08-23 05:07:53.327 INFO 16360 --- [ restartedMain] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=inactiveMemberJob3]] launched with the following parameters: [{}]
2022-08-23 05:07:53.617 INFO 16360 --- [ restartedMain] o.s.batch.core.job.SimpleStepHandler : Executing step: [inactiveMemberStep]
2022-08-23 05:07:53.811 INFO 16360 --- [ restartedMain] o.s.batch.core.step.AbstractStep : Step: [inactiveMemberStep] executed in 194ms
2022-08-23 05:07:53.964 INFO 16360 --- [ restartedMain] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=inactiveMemberJob3]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 565ms
However, when I try to run using joblauncher, there is no log registered in job and only the log corresponding to job start and step start.
2022-08-23 05:08:13.746 INFO 16360 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-08-23 05:08:13.746 INFO 16360 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-08-23 05:08:13.747 INFO 16360 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2022-08-23 05:08:14.015 INFO 16360 --- [nio-8080-exec-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=inactiveMemberJob3]] launched with the following parameters: [{}]
2022-08-23 05:08:14.271 INFO 16360 --- [nio-8080-exec-1] o.s.batch.core.job.SimpleStepHandler : Executing step: [inactiveMemberStep]
2022-08-23 05:08:14.458 INFO 16360 --- [nio-8080-exec-1] o.s.batch.core.step.AbstractStep : Step: [inactiveMemberStep] executed in 187ms
2022-08-23 05:08:14.607 INFO 16360 --- [nio-8080-exec-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=inactiveMemberJob3]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 526ms
2022-08-23 05:08:14.607 INFO 16360 --- [nio-8080-exec-1] c.c.chatting.controller.HomeController : IsRunning : false
2022-08-23 05:08:52.572 INFO 16360 --- [MessageBroker-1] o.s.w.s.c.WebSocketMessageBrokerStats : WebSocketSession[0 current WS(0)-HttpStream(0)-HttpPoll(0), 0 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(0)-CONNECTED(0)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], outboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], sockJsScheduler[pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]
I debugged the run method in the joblauncher, and the incoming values were the same as they were when they were restarted.
Is there anything i'm missing?
HomeController.java
package com.capston.chatting.controller;
import com.capston.chatting.config.batch.InactiveMemberJobConfig;
import com.capston.chatting.dto.GetRoomIdDto;
import com.capston.chatting.entity.ChatRoom;
import com.capston.chatting.entity.Member;
import com.capston.chatting.repository.MemberRepository;
import com.capston.chatting.service.ChatRoomService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.*;
#Controller
#RequiredArgsConstructor
#Slf4j
public class HomeController {
// Test
private final JobLauncher jobLauncher;
private final InactiveMemberJobConfig config;
#GetMapping("/job_start")
#ResponseBody
public String jobStart() {
JobExecution run = null;
try {
run = jobLauncher.run(config.inactiveMemberJob(), new JobParameters());
log.info("IsRunning : {}", run.isRunning());
} catch (Exception e) {
log.error(e.getMessage());
}
return String.valueOf(run.getJobInstance());
}
}
InactiveMemberJobConfig.java
package com.capston.chatting.config.batch;
import com.capston.chatting.entity.Member;
import com.capston.chatting.enums.MemberStatus;
import com.capston.chatting.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime;
import java.util.List;
#Slf4j
#RequiredArgsConstructor
#Configuration
public class InactiveMemberJobConfig {
private final MemberRepository memberRepository;
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
#Bean
public Job inactiveMemberJob() {
log.info("InactiveMemberJob execution");
return jobBuilderFactory.get("inactiveMemberJob3")
.start(inactiveJobStep())
.build();
}
#Bean
public Step inactiveJobStep() {
log.info("InactiveMemberStep execution");
return stepBuilderFactory.get("inactiveMemberStep")
.<Member, Member>chunk(10)
.reader(inactiveMemberReader())
.processor(inactiveMemberProcessor())
.writer(inactiveMemberWriter())
.allowStartIfComplete(true)
.build();
}
#Bean
public ListItemReader<Member> inactiveMemberReader() {
log.info("InactiveMemberReader execution");
List<Member> oldMembers = memberRepository
.findByUpdateDateBeforeAndStatusEquals(LocalDateTime.now().minusYears(1), MemberStatus.ACTIVE);
// ArrayList<Member> collect = oldMembers.stream().map(member -> member.setInactive()).collect(Collectors.toCollection(ArrayList::new));
// memberRepository.saveAll(collect);
return new ListItemReader<>(oldMembers);
}
#Bean
public ItemProcessor<Member, Member> inactiveMemberProcessor() {
log.info("test");
ItemProcessor<Member, Member> memberItemProcessor = (member) -> {
log.info("InactiveMemberProcessor execution");
return member.setInactive();
};
return memberItemProcessor;
// return new ItemProcessor<Member, Member>() {
// #Override
// public Member process(Member member) throws Exception {
// log.info("InactiveMemberProcessor execution");
// return member.setInactive();
// }
// };
// return member -> {
// log.info("InactiveMemberProcessor execution");
// return member.setInactive();
// };
}
#Bean
public ItemWriter<Member> inactiveMemberWriter() {
log.info("InactiveMemberWriter execution");
return ((List<? extends Member> members) -> {
memberRepository.saveAll(members);
log.info("Members : {}", members);
});
}
}
The default bean scope in Spring is singleton. This means that your job/step/reader/processor/writer beans will only be loaded once at application startup, and reused when requested during your application lifetime.
So the logs you defined in your bean definition methods like the following:
#Bean
public Job inactiveMemberJob() {
log.info("InactiveMemberJob execution");
// ...
}
will only be printed when that bean definition is loaded, ie when the Spring application context starts for the first time. Now since you have a web application, that application context is not refreshed on each web request, so those bean definitions will only be loaded once. That's why you see those logs when you first start your app, but not afterwards (unless you restart your application).
I´m starting with Spring Boot for that I´m following a tutorial. In the tutorial, they created the controller with the #RequestMapping and GET method, once they have run the application, in the console is displayed something like this:
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rooms], methods
= GET}" onto java.util.List<..//more lines
But in my case I got an error:
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto
public
org.springframework.http.ResponseEntity>
org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
Why the Mapping is not created?
This is the controller:
package com.frankmoley.london.data.webservice;
import com.frankmoley.london.data.entity.Room;
import com.frankmoley.london.data.repository.RoomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
#RestController
public class RoomController {
#Autowired
private RoomRepository repository;
#RequestMapping(value="/rooms", method= RequestMethod.GET)
List<Room> findAll(#RequestParam(required=false) String roomNumber){
List<Room> rooms = new ArrayList<>();
if(null==roomNumber){
Iterable<Room> results = this.repository.findAll();
results.forEach(room-> {rooms.add(room);});
}else{
Room room = this.repository.findByNumber(roomNumber);
if(null!=room) {
rooms.add(room);
}
}
return rooms;
}
}
Entity:
package com.frankmoley.london.data.entity;
import javax.persistence.*;
#Entity
#Table(name = "ROOM")
public class Room {
#Id
#Column(name = "ROOM_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "NAME")
private String name;
#Column(name = "ROOM_NUMBER")
private String number;
#Column(name = "BED_INFO")
private String info;
//getters and setters
}
Repository:
package com.frankmoley.london.data.repository;
import com.frankmoley.london.data.entity.Room;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface RoomRepository extends CrudRepository<Room, Long> {
Room findByNumber(String number);
}
Following are my logs:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.8.RELEASE)
2019-09-09 21:41:37.074 INFO 25569 --- [ main] SpringRest.spring_rest.Application : Starting Application on prashant-ubuntu with PID 25569 (/home/prashant/workspace/egen/spring-rest/target/spring-rest-1.0.0.jar started by prashant in /home/prashant/workspace/egen/spring-rest/target)
2019-09-09 21:41:37.077 INFO 25569 --- [ main] SpringRest.spring_rest.Application : No active profile set, falling back to default profiles: default
2019-09-09 21:41:37.715 INFO 25569 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-09-09 21:41:37.796 INFO 25569 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 68ms. Found 1 repository interfaces.
2019-09-09 21:41:38.389 INFO 25569 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d6eeeeff] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-09-09 21:41:38.696 INFO 25569 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-09-09 21:41:38.735 INFO 25569 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-09-09 21:41:38.735 INFO 25569 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.24]
2019-09-09 21:41:38.837 INFO 25569 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-09-09 21:41:38.837 INFO 25569 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1701 ms
2019-09-09 21:41:39.124 INFO 25569 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-09-09 21:41:39.415 INFO 25569 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-09-09 21:41:39.463 INFO 25569 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-09-09 21:41:39.525 INFO 25569 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.11.Final}
2019-09-09 21:41:39.526 INFO 25569 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-09-09 21:41:39.662 INFO 25569 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-09-09 21:41:39.866 INFO 25569 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-09-09 21:41:40.463 INFO 25569 --- [ main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2019-09-09 21:41:40.559 INFO 25569 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-09-09 21:41:41.041 INFO 25569 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-09 21:41:41.114 WARN 25569 --- [ main] 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
2019-09-09 21:41:41.380 INFO 25569 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-09-09 21:41:41.382 INFO 25569 --- [ main] SpringRest.spring_rest.Application : Started Application in 4.703 seconds (JVM running for 5.103)
2019-09-09 21:42:03.922 INFO 25569 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-09-09 21:42:03.922 INFO 25569 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-09-09 21:42:03.934 INFO 25569 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 12 ms
Hibernate: select employee0_.id as id1_0_, employee0_.email as email2_0_, employee0_.name as name3_0_, employee0_.salary as salary4_0_ from employee employee0_
you can clearly see that there aren't any references of RequestMappingHandlerMapping
But still the service is hosted at "/".
I have used the following URL:
http://localhost:8080/employees/springEntityManagerJpa
With other spring application which is not spring boot, the URL is as follows:
http://localhost:8080/spring-rest/api/employees/springEntityManagerJpa
I assume your is the similar case. May be the service is up, but you are providing the wrong endpoints. Just remove the context path. In my case I removed /spring-rest/api
Hope this helps!!!
I have 2 REST controllers in my Spring Boot application with simple CRUD operations.
REST controller, that is mapped to "/json/currency"
package ua.alekstar.moneysaver.rest;
import org.springframework.web.bind.annotation.*;
import ua.alekstar.moneysaver.rest.currency.Currencies;
import ua.alekstar.moneysaver.rest.currency.Currency;
import ua.alekstar.moneysaver.service.CurrencyService;
import java.util.Collections;
#RestController("/json/currency")
public class CurrencyJsonRestController {
private final CurrencyService currencyService;
public CurrencyJsonRestController(CurrencyService currencyService) {
this.currencyService = currencyService;
}
#GetMapping
#ResponseBody
public Currencies get(#RequestParam(required = false) Long id) {
if (id == null) {
return readAll();
}
return read(id);
}
private Currencies read(Long id) {
return new Currencies(Collections.singletonList(currencyService.read(id)));
}
private Currencies readAll() {
return new Currencies(currencyService.readAll());
}
#PostMapping
public void post(#RequestBody Currency currency) {
currencyService.create(currency.toEntity());
}
#PutMapping
public void put(#RequestBody Currency currency) {
currencyService.update(currency.toEntity());
}
#DeleteMapping
public void delete(#RequestParam Long id) {
currencyService.delete(id);
}
}
and REST controller, that is mapped to "/json/account"
package ua.alekstar.moneysaver.rest;
import org.springframework.web.bind.annotation.*;
import ua.alekstar.moneysaver.dao.entities.Currency;
import ua.alekstar.moneysaver.rest.account.Account;
import ua.alekstar.moneysaver.rest.account.Accounts;
import ua.alekstar.moneysaver.service.AccountService;
import ua.alekstar.moneysaver.service.CurrencyService;
import java.util.Collections;
#RestController("/json/account")
public class AccountJsonRestController {
private final AccountService accountService;
private final CurrencyService currencyService;
public AccountJsonRestController(AccountService accountService, CurrencyService currencyService) {
this.accountService = accountService;
this.currencyService = currencyService;
}
#GetMapping
#ResponseBody
public Accounts get(#RequestParam(required = false) Long id) {
if (id == null) {
return readAll();
}
return read(id);
}
private Accounts read(Long id) {
return new Accounts(Collections.singletonList(accountService.read(id)));
}
private Accounts readAll() {
return new Accounts(accountService.readAll());
}
#PostMapping
public void post(#RequestBody Account account) {
accountService.create(toEntity(account));
}
private ua.alekstar.moneysaver.dao.entities.Account toEntity(Account account) {
final Currency currency = currencyService.readByIsoCode(account.getCurrency());
return new ua.alekstar.moneysaver.dao.entities.Account(account.getId(), account.getName(), currency);
}
#PutMapping
public void put(#RequestBody Account account) {
accountService.update(toEntity(account));
}
#DeleteMapping
public void delete(#RequestParam Long id) {
accountService.delete(id);
}
}
While I start my application I have an exception and I do not understand why it happens.
/usr/lib/jvm/java-8-oracle/bin/java -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -javaagent:/home/sasha/Applications/idea-IU-171.3780.107/lib/idea_rt.jar=32820:/home/sasha/Applications/idea-IU-171.3780.107/bin -Dfile.encoding=UTF-8 -classpath /usr/lib/jvm/java-8-oracle/jre/lib/charsets.jar:/usr/lib/jvm/java-8-oracle/jre/lib/deploy.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/cldrdata.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/dnsns.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/jaccess.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/jfxrt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/localedata.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/nashorn.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunec.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/zipfs.jar:/usr/lib/jvm/java-8-oracle/jre/lib/javaws.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jce.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfr.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfxswt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jsse.jar:/usr/lib/jvm/java-8-oracle/jre/lib/management-agent.jar:/usr/lib/jvm/java-8-oracle/jre/lib/plugin.jar:/usr/lib/jvm/java-8-oracle/jre/lib/resources.jar:/usr/lib/jvm/java-8-oracle/jre/lib/rt.jar:/home/sasha/Documents/development/moneysaver/target/classes:/home/sasha/.m2/repository/org/springframework/boot/spring-boot-starter-data-jpa/1.5.3.RELEASE/spring-boot-starter-data-jpa-1.5.3.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/boot/spring-boot-starter/1.5.3.RELEASE/spring-boot-starter-1.5.3.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/boot/spring-boot/1.5.3.RELEASE/spring-boot-1.5.3.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/1.5.3.RELEASE/spring-boot-autoconfigure-1.5.3.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/boot/spring-boot-starter-logging/1.5.3.RELEASE/spring-boot-starter-logging-1.5.3.RELEASE.jar:/home/sasha/.m2/repository/ch/qos/logback/logback-classic/1.1.11/logback-classic-1.1.11.jar:/home/sasha/.m2/repository/ch/qos/logback/logback-core/1.1.11/logback-core-1.1.11.jar:/home/sasha/.m2/repository/org/slf4j/jul-to-slf4j/1.7.25/jul-to-slf4j-1.7.25.jar:/home/sasha/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.25/log4j-over-slf4j-1.7.25.jar:/home/sasha/.m2/repository/org/yaml/snakeyaml/1.17/snakeyaml-1.17.jar:/home/sasha/.m2/repository/org/springframework/boot/spring-boot-starter-aop/1.5.3.RELEASE/spring-boot-starter-aop-1.5.3.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/spring-aop/4.3.8.RELEASE/spring-aop-4.3.8.RELEASE.jar:/home/sasha/.m2/repository/org/aspectj/aspectjweaver/1.8.10/aspectjweaver-1.8.10.jar:/home/sasha/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/1.5.3.RELEASE/spring-boot-starter-jdbc-1.5.3.RELEASE.jar:/home/sasha/.m2/repository/org/apache/tomcat/tomcat-jdbc/8.5.14/tomcat-jdbc-8.5.14.jar:/home/sasha/.m2/repository/org/apache/tomcat/tomcat-juli/8.5.14/tomcat-juli-8.5.14.jar:/home/sasha/.m2/repository/org/springframework/spring-jdbc/4.3.8.RELEASE/spring-jdbc-4.3.8.RELEASE.jar:/home/sasha/.m2/repository/javax/transaction/javax.transaction-api/1.2/javax.transaction-api-1.2.jar:/home/sasha/.m2/repository/org/springframework/data/spring-data-jpa/1.11.3.RELEASE/spring-data-jpa-1.11.3.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/data/spring-data-commons/1.13.3.RELEASE/spring-data-commons-1.13.3.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/spring-orm/4.3.8.RELEASE/spring-orm-4.3.8.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/spring-context/4.3.8.RELEASE/spring-context-4.3.8.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/spring-tx/4.3.8.RELEASE/spring-tx-4.3.8.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/spring-beans/4.3.8.RELEASE/spring-beans-4.3.8.RELEASE.jar:/home/sasha/.m2/repository/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar:/home/sasha/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.25/jcl-over-slf4j-1.7.25.jar:/home/sasha/.m2/repository/org/springframework/spring-aspects/4.3.8.RELEASE/spring-aspects-4.3.8.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/boot/spring-boot-starter-web/1.5.3.RELEASE/spring-boot-starter-web-1.5.3.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/1.5.3.RELEASE/spring-boot-starter-tomcat-1.5.3.RELEASE.jar:/home/sasha/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.5.14/tomcat-embed-core-8.5.14.jar:/home/sasha/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/8.5.14/tomcat-embed-el-8.5.14.jar:/home/sasha/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/8.5.14/tomcat-embed-websocket-8.5.14.jar:/home/sasha/.m2/repository/org/hibernate/hibernate-validator/5.3.5.Final/hibernate-validator-5.3.5.Final.jar:/home/sasha/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar:/home/sasha/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.8.8/jackson-databind-2.8.8.jar:/home/sasha/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.8.0/jackson-annotations-2.8.0.jar:/home/sasha/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.8.8/jackson-core-2.8.8.jar:/home/sasha/.m2/repository/org/springframework/spring-web/4.3.8.RELEASE/spring-web-4.3.8.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/spring-webmvc/4.3.8.RELEASE/spring-webmvc-4.3.8.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/spring-expression/4.3.8.RELEASE/spring-expression-4.3.8.RELEASE.jar:/home/sasha/.m2/repository/org/springframework/spring-core/4.3.8.RELEASE/spring-core-4.3.8.RELEASE.jar:/home/sasha/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.0-api/1.0.1.Final/hibernate-jpa-2.0-api-1.0.1.Final.jar:/home/sasha/.m2/repository/org/hibernate/hibernate-core/5.2.10.Final/hibernate-core-5.2.10.Final.jar:/home/sasha/.m2/repository/org/jboss/logging/jboss-logging/3.3.1.Final/jboss-logging-3.3.1.Final.jar:/home/sasha/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar:/home/sasha/.m2/repository/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar:/home/sasha/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar:/home/sasha/.m2/repository/org/jboss/spec/javax/transaction/jboss-transaction-api_1.2_spec/1.0.1.Final/jboss-transaction-api_1.2_spec-1.0.1.Final.jar:/home/sasha/.m2/repository/org/jboss/jandex/2.0.3.Final/jandex-2.0.3.Final.jar:/home/sasha/.m2/repository/com/fasterxml/classmate/1.3.3/classmate-1.3.3.jar:/home/sasha/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar:/home/sasha/.m2/repository/org/hibernate/common/hibernate-commons-annotations/5.0.1.Final/hibernate-commons-annotations-5.0.1.Final.jar:/home/sasha/.m2/repository/org/hibernate/hibernate-entitymanager/5.2.10.Final/hibernate-entitymanager-5.2.10.Final.jar:/home/sasha/.m2/repository/net/bytebuddy/byte-buddy/1.6.6/byte-buddy-1.6.6.jar:/home/sasha/.m2/repository/org/hibernate/hibernate-ehcache/5.2.10.Final/hibernate-ehcache-5.2.10.Final.jar:/home/sasha/.m2/repository/net/sf/ehcache/ehcache/2.10.4/ehcache-2.10.4.jar:/home/sasha/.m2/repository/com/mchange/c3p0/0.9.5.2/c3p0-0.9.5.2.jar:/home/sasha/.m2/repository/com/mchange/mchange-commons-java/0.2.11/mchange-commons-java-0.2.11.jar:/home/sasha/.m2/repository/org/postgresql/postgresql/42.0.0/postgresql-42.0.0.jar ua.alekstar.moneysaver.MoneysaverApplication
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.3.RELEASE)
2017-05-13 21:15:20.109 INFO 9745 --- [ main] u.a.moneysaver.MoneysaverApplication : Starting MoneysaverApplication on sasha-pc with PID 9745 (/home/sasha/Documents/development/moneysaver/target/classes started by sasha in /home/sasha/Documents/development/moneysaver)
2017-05-13 21:15:20.112 INFO 9745 --- [ main] u.a.moneysaver.MoneysaverApplication : No active profile set, falling back to default profiles: default
2017-05-13 21:15:20.165 INFO 9745 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#319b92f3: startup date [Sat May 13 21:15:20 EEST 2017]; root of context hierarchy
2017-05-13 21:15:22.043 INFO 9745 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-05-13 21:15:22.053 INFO 9745 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2017-05-13 21:15:22.054 INFO 9745 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.14
2017-05-13 21:15:22.147 INFO 9745 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-05-13 21:15:22.147 INFO 9745 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1985 ms
2017-05-13 21:15:22.259 INFO 9745 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-05-13 21:15:22.262 INFO 9745 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-05-13 21:15:22.263 INFO 9745 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-05-13 21:15:22.263 INFO 9745 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-05-13 21:15:22.263 INFO 9745 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-05-13 21:15:22.311 INFO 9745 --- [g-Init-Reporter] com.mchange.v2.log.MLog : MLog clients using slf4j logging.
2017-05-13 21:15:22.394 INFO 9745 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-05-13 21:15:22.404 INFO 9745 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-05-13 21:15:22.468 INFO 9745 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.2.10.Final}
2017-05-13 21:15:22.470 INFO 9745 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-05-13 21:15:22.503 INFO 9745 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-05-13 21:15:22.628 INFO 9745 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL94Dialect
2017-05-13 21:15:22.737 INFO 9745 --- [ main] o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2017-05-13 21:15:22.739 INFO 9745 --- [ main] org.hibernate.type.BasicTypeRegistry : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#1e008f36
2017-05-13 21:15:23.195 INFO 9745 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-05-13 21:15:23.645 INFO 9745 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#319b92f3: startup date [Sat May 13 21:15:20 EEST 2017]; root of context hierarchy
2017-05-13 21:15:23.697 INFO 9745 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[],methods=[POST]}" onto public void ua.alekstar.moneysaver.rest.AccountJsonRestController.post(ua.alekstar.moneysaver.rest.account.Account)
2017-05-13 21:15:23.698 INFO 9745 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[],methods=[GET]}" onto public ua.alekstar.moneysaver.rest.account.Accounts ua.alekstar.moneysaver.rest.AccountJsonRestController.get(java.lang.Long)
2017-05-13 21:15:23.698 INFO 9745 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[],methods=[PUT]}" onto public void ua.alekstar.moneysaver.rest.AccountJsonRestController.put(ua.alekstar.moneysaver.rest.account.Account)
2017-05-13 21:15:23.698 INFO 9745 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[],methods=[DELETE]}" onto public void ua.alekstar.moneysaver.rest.AccountJsonRestController.delete(java.lang.Long)
2017-05-13 21:15:23.700 WARN 9745 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map '/json/currency' method
public void ua.alekstar.moneysaver.rest.CurrencyJsonRestController.post(ua.alekstar.moneysaver.rest.currency.Currency)
to {[],methods=[POST]}: There is already '/json/account' bean method
public void ua.alekstar.moneysaver.rest.AccountJsonRestController.post(ua.alekstar.moneysaver.rest.account.Account) mapped.
2017-05-13 21:15:23.701 INFO 9745 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-05-13 21:15:23.703 INFO 9745 --- [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
2017-05-13 21:15:23.716 INFO 9745 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-05-13 21:15:23.722 ERROR 9745 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map '/json/currency' method
public void ua.alekstar.moneysaver.rest.CurrencyJsonRestController.post(ua.alekstar.moneysaver.rest.currency.Currency)
to {[],methods=[POST]}: There is already '/json/account' bean method
public void ua.alekstar.moneysaver.rest.AccountJsonRestController.post(ua.alekstar.moneysaver.rest.account.Account) mapped.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at ua.alekstar.moneysaver.MoneysaverApplication.main(MoneysaverApplication.java:10) [classes/:na]
Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map '/json/currency' method
public void ua.alekstar.moneysaver.rest.CurrencyJsonRestController.post(ua.alekstar.moneysaver.rest.currency.Currency)
to {[],methods=[POST]}: There is already '/json/account' bean method
public void ua.alekstar.moneysaver.rest.AccountJsonRestController.post(ua.alekstar.moneysaver.rest.account.Account) mapped.
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.assertUniqueMethodMapping(AbstractHandlerMethodMapping.java:576) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:540) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:264) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:250) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:214) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:184) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:127) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
... 16 common frames omitted
Process finished with exit code 1
After I remove one of the REST controllers the application runs successfully. What should I do to solve this issue?
#RestController("/json/currency") is different from
#RestController
#RequestMapping("/json/currency")
Read #RestController documentation here https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html
change your
declaration like this
#RestController
#RequestMapping("......") in both the classes. It should work
Since this answer appears on top of google searches, and my problem was a bit different, I am posting my solution:
I got the Spring Boot Ambiguous mapping. Cannot map method error.
The problem:
I had two controller methods with same #RequestMapping which were conflicting. Copy/paste mistake :)
The fix:
Change to appropriate #RequestMapping.
I've been working through the following tutorial:
http://spring.io/guides/gs/rest-service/
I was initially able to get the code to work correctly (Run the finished tutorial, send an HTTP message and get the correct response) and successfully expand upon it.
After expanding further, I ran into the following exception:
java.lang.IllegalStateException: Could not evaluate condition on org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer due to internal class not found. This can happen if you are #ComponentScanning a springframework package (e.g. if you put a #ComponentScan in the default package by mistake)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:51)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:92)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:174)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:136)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:330)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:611)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:961)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:950)
at com.aharrison.hello.Application.main(Application.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
I've since stripped the code back down to only what is shown in the example, but I am still experiencing the exception.
I think it could possibly be related to the following issue, although it is marked as closed:
https://github.com/spring-projects/spring-boot/issues/2050
I'm not very experienced with Spring, so I can't fully comprehend what is being discussed.
Here are my current classes:
Greeting.java:
package com.aharrison.hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
GreetingController:
package com.aharrison.hello;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicLong;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
Application.java :
package com.aharrison.hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
/**
* Created by Adam on 12/26/2014.
*/
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
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.aharrison</groupId>
<artifactId>SpringRestAPI</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.6.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.2</version>
</dependency>
</dependencies>
Questions:
What is causing the exception in this situation? Is there something wrong with my code above, or is the problem environment related?
When the exception says "..if you put a #ComponentScan in the default package by mistake", which is the default package it is referring to? Is this applicable to the current situation?
Thanks in advance.
When I run the code that you have provided everything works fine. The only change I had to make was in the pom.xml where I added the following:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.0.RELEASE</version>
</parent>
This enables the whole Spring Boot mechanism and is required in order for you to be able to start the application.
See below for the successful output from my test run:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.2.0.RELEASE)
2014-12-27 17:41:12.472 INFO 4065 --- [ main] com.aharrison.hello.Application : Starting Application on My-MacBook-Pro.local with PID 4065 (/Users/wassgren/test/target/test-classes started by wassgren in /Users/wassgren/test/test-di)
2014-12-27 17:41:12.506 INFO 4065 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4a668b6e: startup date [Sat Dec 27 17:41:12 CET 2014]; root of context hierarchy
2014-12-27 17:41:13.407 INFO 4065 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2014-12-27 17:41:14.186 INFO 4065 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration' of type [class org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-12-27 17:41:14.703 INFO 4065 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080/http
2014-12-27 17:41:15.047 INFO 4065 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2014-12-27 17:41:15.048 INFO 4065 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.15
2014-12-27 17:41:15.154 INFO 4065 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2014-12-27 17:41:15.154 INFO 4065 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2651 ms
2014-12-27 17:41:16.399 INFO 4065 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2014-12-27 17:41:16.404 INFO 4065 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2014-12-27 17:41:16.404 INFO 4065 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2014-12-27 17:41:16.907 INFO 4065 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4a668b6e: startup date [Sat Dec 27 17:41:12 CET 2014]; root of context hierarchy
2014-12-27 17:41:16.979 INFO 4065 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public com.aharrison.hello.Greeting com.aharrison.hello.GreetingController.greeting(java.lang.String)
2014-12-27 17:41:16.981 INFO 4065 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2014-12-27 17:41:16.981 INFO 4065 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2014-12-27 17:41:17.013 INFO 4065 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-12-27 17:41:17.014 INFO 4065 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-12-27 17:41:17.059 INFO 4065 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-12-27 17:41:17.206 INFO 4065 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2014-12-27 17:41:17.292 INFO 4065 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080/http
2014-12-27 17:41:17.294 INFO 4065 --- [ main] com.aharrison.hello.Application : Started Application in 5.245 seconds (JVM running for 6.088)
Remove the #ComponentScan which is placed above the Application class. #SpringBootApplication adds it by default, if the classes you need to be scanned are within the same package as the Application class.
Placing #SpringBootApplication annotation on the application class and placing the application class in the same package or the parent package of the called classes will fix the issue.
Spring Boot 1.2.2 is released, I would advice to upgrade to the new version as it comes with a significant number of fixes. Also it uses the spring-security 3.2.6. You would have to be very careful when you declare any or override dependencies other than the ones that come by default, as the boot already comes with most of it. I had the same problem with using the spring boot 1.2.2 with spring security 3.2.5 but when i rolled back to spring boot 1.2.1 everything was fine.