I am trying to create a basic spring boot application (JDK 1.8) with a REST API .
The following is my application code
package org.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("org.demo")
#EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
I have added a simple controller as follows
package org.demo.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#RestController(value = "/hello")
public class HelloController {
#GetMapping
#ResponseBody
public String hello() {
return "Hello";
}
}
The POM file of my project is as follows
<?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>org.demo</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
When I run this application, it starts successfully. However, when I try to hit the URL localhost:8080 or loclahost:8080/hello, I get the 404 error message
The following are the startup logs
:: Spring Boot :: (v2.0.1.RELEASE)
2018-04-24 21:51:38.888 INFO 12068 --- [ main] org.demo.DemoApplication : Starting DemoApplication on DESKTOP-G2QR23G with PID 12068 (I:\demo\spring-boot\demo\target\classes started by chirayu in I:\demo\spring-boot\demo)
2018-04-24 21:51:38.892 INFO 12068 --- [ main] org.demo.DemoApplication : No active profile set, falling back to default profiles: default
2018-04-24 21:51:38.970 INFO 12068 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#5745ca0e: startup date [Tue Apr 24 21:51:38 IST 2018]; root of context hierarchy
2018-04-24 21:51:39.617 INFO 12068 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-04-24 21:51:39.999 INFO 12068 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-04-24 21:51:40.030 INFO 12068 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-04-24 21:51:40.030 INFO 12068 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.29
2018-04-24 21:51:40.043 INFO 12068 --- [ost-startStop-1] 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: [I:\Program Files\Java\jdk1.8.0_66\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;I:\Program Files\Java\jdk1.8.0_66\bin;I:\Program Files\nodejs\;C:\Program Files (x86)\GtkSharp\2.12\bin;C:\Program Files (x86)\Skype\Phone\;I:\MinGW\bin;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 ^& MySQL Utilities 1.5\;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 ^& MySQL Utilities 1.5\Doctrine extensions for PHP\;I:\Program Files (x86)\maven\apache-maven-3.3.9\bin\;I:\Program Files (x86)\Heroku\bin;C:\Program Files (x86)\git\cmd;I:\Program Files\Git\cmd;I:\Program Files\PostgreSQL\9.6\bin;I:\RailsInstaller\Git\cmd;I:\RailsInstaller\Ruby2.2.0\bin;I:\Program Files (x86)\Python\Scripts\;I:\Program Files (x86)\Python\;C:\Users\chirayu\AppData\Roaming\npm;C:\Users\chirayu\AppData\Local\Microsoft\WindowsApps;I:\Program Files (x86)\Microsoft VS Code\bin;;.]
2018-04-24 21:51:40.164 INFO 12068 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-04-24 21:51:40.164 INFO 12068 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1198 ms
2018-04-24 21:51:40.215 INFO 12068 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-04-24 21:51:40.598 INFO 12068 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-04-24 21:51:40.633 INFO 12068 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-04-24 21:51:40.638 INFO 12068 --- [ main] org.demo.DemoApplication : Started DemoApplication in 2.2 seconds (JVM running for 2.797)
I am not sure what I might be missing. Please help.
I got the solution. It was due to package visibility. Main class was not able to found package in which controller class is present. So added all classes under same package. You can also place application class one level up. Got help from below link:
Spring Boot: Cannot access REST Controller on localhost (404)
Test as follow... did the trick for me remove the path from the notation #RestController then add the path #GetMapping notation as follow #GetMapping("/hello") test http://localhost:8080/hello you should get a correct response in order to have a response for this request http://localhost:8080/hello/hello need to add the follow:
#RestController
#RequestMapping(value = "/hello")
change to :
#RestController
#RequestMapping(value = "hello-controller")
public class HelloController {
#GetMapping(value="hello")
#ResponseBody
public String hello() {
return "Hello";
}
}
so you can use your api from : localhost:8080/hello-controller/hello
value in #RequestMapping below #RestController is define your class address.
value in #GetMapping is for your API address.
Hope this explanation help you.
Related
There is a code:
package com.example.sweater3.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Message {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String text;
private String tag;
public Message() {
}
public Message(String text, String tag) {
this.text = text;
this.tag = tag;
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
_
package com.example.sweater3.repos;
import com.example.sweater3.domain.Message;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface MessageRepo extends CrudRepository<Message, Long> {
List<Message> findByTag(String tag);
}
__
package com.example.sweater3;
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);
}
}
__
package com.example.sweater3;
import com.example.sweater3.repos.MessageRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
#Controller
public class GreetingController {
#Autowired
private MessageRepo messageRepo;
}
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.example</groupId>
<artifactId>sweater3</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mustache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.1.9.RELEASE</version>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
When the program starts, such an error crashes:
:: Spring Boot :: (v2.0.0.RELEASE)
2019-10-30 21:28:05.351 INFO 4044 --- [ restartedMain] com.example.sweater3.Application : Starting Application on IlyaPC with PID 4044 (D:\EPAM\1Spring2019(04.19-09.19)\My\TEST\5October\30\sweater3\target\classes started by Ilya in D:\EPAM\1Spring2019(04.19-09.19)\My\TEST\5October\30\sweater3)
2019-10-30 21:28:05.354 INFO 4044 --- [ restartedMain] com.example.sweater3.Application : No active profile set, falling back to default profiles: default
2019-10-30 21:28:05.779 INFO 4044 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#7f8d5a6e: startup date [Wed Oct 30 21:28:05 MSK 2019]; root of context hierarchy
2019-10-30 21:28:10.905 INFO 4044 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-10-30 21:28:10.967 INFO 4044 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-10-30 21:28:10.968 INFO 4044 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28
2019-10-30 21:28:10.985 INFO 4044 --- [ost-startStop-1] 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\jdk1.8.0_212\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files\Java\jdk-12.0.1\bin\;C:\Program Files\Java\jdk1.8.0_212\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\Java\jre1.8.0_221\bin;C:\Users\Илья\AppData\Roaming\npm;.]
2019-10-30 21:28:11.243 INFO 4044 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-10-30 21:28:11.244 INFO 4044 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 5477 ms
2019-10-30 21:28:11.646 INFO 4044 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2019-10-30 21:28:11.656 INFO 4044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-10-30 21:28:11.657 INFO 4044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-10-30 21:28:11.657 INFO 4044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-10-30 21:28:11.657 INFO 4044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2019-10-30 21:28:11.741 WARN 4044 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'greetingController': Unsatisfied dependency expressed through field 'messageRepo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.sweater3.repos.MessageRepo' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2019-10-30 21:28:11.745 INFO 4044 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-10-30 21:28:11.780 INFO 4044 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-10-30 21:28:12.257 ERROR 4044 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field messageRepo in com.example.sweater3.GreetingController required a bean of type 'com.example.sweater3.repos.MessageRepo' that could not be found.
Action:
Consider defining a bean of type 'com.example.sweater3.repos.MessageRepo' in your configuration.
If I comment on the #Autowired annotation everything works.
What is the problem and how to solve?
p.s. The code is as simplified as possible, since I removed extra pieces so that they would not interfere with reading the code and clutter up the review.
upd:
Response to comments:
1. Adina Fometescu https://stackoverflow.com/a/58631848/11688668
after adding the following error appears -
2019-10-30 21:46:01.861 WARN 2716 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'inMemoryDatabaseShutdownExecutor' defined in class path resource [org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.class]: Unsatisfied dependency expressed through method 'inMemoryDatabaseShutdownExecutor' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
2019-10-30 21:46:01.885 INFO 2716 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-10-30 21:46:01.943 INFO 2716 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-10-30 21:46:01.970 ERROR 2716 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
You must enable repositories in your application :
#SpringBootApplication
#EnableJpaRepositories
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Also make sure that you add :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
UPDATE :
You must configure your database connection and driver. Example with H2 (in memory database)
Add new dependency:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
In application.properties add:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
I am trying to develop a sample spring boot application that has spring JPA and Hibernate implementation. While I managed to get my setup complete, I am getting the following error while running the application.
Error creating bean with name
'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration'
I suspect this is some kind of configuration based error, but I am unable to pin point the source of the error.
I have seen some posts with this error and tried those resolutions. But those didn't help me resolve the error.
Here is my application's setup.
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.shandesh</groupId>
<artifactId>training</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.16</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml file :-
spring:
profiles: dev
datasource:
url: jdbc:oracle:thin:#//localhost:1521/orcl
driverClassName: oracle.jdbc.driver.OracleDriver
username: ****
password: ****
jpa:
show_sql: true
generate-ddl: false
hibernate:
ddl-auto: none
properties:
hibernate.dialect: org.hibernate.dialect.OracleDialect
Entity class :-
package com.shandesh.dao;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.sql.Timestamp;
#Getter
#Setter
#Entity
#Table(name = "APPUSER")
public class AppUserDTO {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "USER_ID")
Long userId;
#Column(name = "USER_NAME")
String userName;
#Column(name = "USER_FIRST_NAME")
String userFirstName;
#Column(name = "USER_LAST_NAME")
String userLastName;
#Column(name = "LAST_UPDATED_BY")
String lastUpdatedBy;
#Column(name = "LAST_UPDATED_DATE")
Timestamp lastUpdatedDate;
}
Repository class :-
package com.shandesh.repository;
import com.shandesh.dao.AppUserDTO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.List;
#Repository
public interface AppUserRepository extends JpaRepository<AppUserDTO, Integer> {
List<AppUserDTO> findByUserName(String userName);
List<AppUserDTO> findByUserId(Integer userId);
List<AppUserDTO> findAll();
#Modifying
Long deleteByUserName(String userName);
#Modifying
Long deleteByUserid(Integer userId);
}
Service class :-
package com.shandesh.service;
import com.shandesh.dao.AppUserDTO;
import com.shandesh.repository.AppUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class AppUserService {
#Autowired
private AppUserRepository appUserRepository;
public List<AppUserDTO> getAllAppUsers() {
return appUserRepository.findAll();
}
}
Controller class :-
package com.shandesh.controller;
import com.shandesh.dao.AppUserDTO;
import com.shandesh.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#EnableAutoConfiguration //(exclude={DataSourceAutoConfiguration.class})
public class UserController {
#Autowired
private AppUserService appUserService;
#RequestMapping(value = "/getAllUsers", produces = MediaType.APPLICATION_JSON_VALUE)
public List<AppUserDTO> getAllUsers() { return appUserService.getAllAppUsers(); }
}
Stack trace while running the application via IntelliJ console.
"C:\Program Files\Java\jdk1.8.0_141\bin\java.exe" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.1.2\lib\idea_rt.jar=50180:C:\Program Files\JetBrains\IntelliJ IDEA 2019.1.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_141\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_141\jre\lib\rt.jar;G:\Shantanu\Learning\Technology\Projects\training\target\classes;C:\Users\Shantanu.m2\repository\org\springframework\boot\spring-boot-starter-web\2.1.0.RELEASE\spring-boot-starter-web-2.1.0.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\boot\spring-boot-starter\2.1.0.RELEASE\spring-boot-starter-2.1.0.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\boot\spring-boot\2.1.0.RELEASE\spring-boot-2.1.0.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.1.0.RELEASE\spring-boot-autoconfigure-2.1.0.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\boot\spring-boot-starter-logging\2.1.0.RELEASE\spring-boot-starter-logging-2.1.0.RELEASE.jar;C:\Users\Shantanu.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\Shantanu.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\Shantanu.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.11.1\log4j-to-slf4j-2.11.1.jar;C:\Users\Shantanu.m2\repository\org\apache\logging\log4j\log4j-api\2.11.1\log4j-api-2.11.1.jar;C:\Users\Shantanu.m2\repository\org\slf4j\jul-to-slf4j\1.7.25\jul-to-slf4j-1.7.25.jar;C:\Users\Shantanu.m2\repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-core\5.1.2.RELEASE\spring-core-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-jcl\5.1.2.RELEASE\spring-jcl-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\yaml\snakeyaml\1.23\snakeyaml-1.23.jar;C:\Users\Shantanu.m2\repository\org\springframework\boot\spring-boot-starter-json\2.1.0.RELEASE\spring-boot-starter-json-2.1.0.RELEASE.jar;C:\Users\Shantanu.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.9.7\jackson-databind-2.9.7.jar;C:\Users\Shantanu.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;C:\Users\Shantanu.m2\repository\com\fasterxml\jackson\core\jackson-core\2.9.7\jackson-core-2.9.7.jar;C:\Users\Shantanu.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.7\jackson-datatype-jdk8-2.9.7.jar;C:\Users\Shantanu.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.7\jackson-datatype-jsr310-2.9.7.jar;C:\Users\Shantanu.m2\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.7\jackson-module-parameter-names-2.9.7.jar;C:\Users\Shantanu.m2\repository\org\springframework\boot\spring-boot-starter-tomcat\2.1.0.RELEASE\spring-boot-starter-tomcat-2.1.0.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.12\tomcat-embed-core-9.0.12.jar;C:\Users\Shantanu.m2\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.12\tomcat-embed-el-9.0.12.jar;C:\Users\Shantanu.m2\repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.12\tomcat-embed-websocket-9.0.12.jar;C:\Users\Shantanu.m2\repository\org\hibernate\validator\hibernate-validator\6.0.13.Final\hibernate-validator-6.0.13.Final.jar;C:\Users\Shantanu.m2\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-web\5.1.2.RELEASE\spring-web-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-beans\5.1.2.RELEASE\spring-beans-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-webmvc\5.1.2.RELEASE\spring-webmvc-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-aop\5.1.2.RELEASE\spring-aop-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-context\5.1.2.RELEASE\spring-context-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-expression\5.1.2.RELEASE\spring-expression-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\com\oracle\ojdbc6\11.2.0.4\ojdbc6-11.2.0.4.jar;C:\Users\Shantanu.m2\repository\org\springframework\boot\spring-boot-starter-data-jpa\2.1.0.RELEASE\spring-boot-starter-data-jpa-2.1.0.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\boot\spring-boot-starter-aop\2.1.0.RELEASE\spring-boot-starter-aop-2.1.0.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\aspectj\aspectjweaver\1.9.2\aspectjweaver-1.9.2.jar;C:\Users\Shantanu.m2\repository\javax\transaction\javax.transaction-api\1.3\javax.transaction-api-1.3.jar;C:\Users\Shantanu.m2\repository\javax\xml\bind\jaxb-api\2.3.1\jaxb-api-2.3.1.jar;C:\Users\Shantanu.m2\repository\org\springframework\data\spring-data-jpa\2.1.2.RELEASE\spring-data-jpa-2.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\data\spring-data-commons\2.1.2.RELEASE\spring-data-commons-2.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-orm\5.1.2.RELEASE\spring-orm-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-tx\5.1.2.RELEASE\spring-tx-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-aspects\5.1.2.RELEASE\spring-aspects-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\com\zaxxer\HikariCP\2.6.0\HikariCP-2.6.0.jar;C:\Users\Shantanu.m2\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;C:\Users\Shantanu.m2\repository\org\springframework\boot\spring-boot-starter-jdbc\2.1.0.RELEASE\spring-boot-starter-jdbc-2.1.0.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\springframework\spring-jdbc\5.1.2.RELEASE\spring-jdbc-5.1.2.RELEASE.jar;C:\Users\Shantanu.m2\repository\org\projectlombok\lombok\1.16.16\lombok-1.16.16.jar;C:\Users\Shantanu.m2\repository\org\hibernate\hibernate-core\5.3.7.Final\hibernate-core-5.3.7.Final.jar;C:\Users\Shantanu.m2\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;C:\Users\Shantanu.m2\repository\javax\persistence\javax.persistence-api\2.2\javax.persistence-api-2.2.jar;C:\Users\Shantanu.m2\repository\org\javassist\javassist\3.23.1-GA\javassist-3.23.1-GA.jar;C:\Users\Shantanu.m2\repository\net\bytebuddy\byte-buddy\1.9.3\byte-buddy-1.9.3.jar;C:\Users\Shantanu.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\Shantanu.m2\repository\org\jboss\spec\javax\transaction\jboss-transaction-api_1.2_spec\1.1.1.Final\jboss-transaction-api_1.2_spec-1.1.1.Final.jar;C:\Users\Shantanu.m2\repository\org\jboss\jandex\2.0.5.Final\jandex-2.0.5.Final.jar;C:\Users\Shantanu.m2\repository\com\fasterxml\classmate\1.4.0\classmate-1.4.0.jar;C:\Users\Shantanu.m2\repository\javax\activation\javax.activation-api\1.2.0\javax.activation-api-1.2.0.jar;C:\Users\Shantanu.m2\repository\org\dom4j\dom4j\2.1.1\dom4j-2.1.1.jar;C:\Users\Shantanu.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.0.4.Final\hibernate-commons-annotations-5.0.4.Final.jar;C:\Users\Shantanu.m2\repository\org\hibernate\hibernate-entitymanager\5.3.7.Final\hibernate-entitymanager-5.3.7.Final.jar" com.shandesh.Application
. ____ _ __ _ _
/\ / ' __ _ ()_ __ __ _ \ \ \ \
( ( )_ | '_ | '| | ' / ` | \ \ \ \
\/ )| |)| | | | | || (| | ) ) ) )
' |____| .|| ||| |__, | / / / /
=========|_|==============|___/=///_/
:: Spring Boot :: (v2.1.0.RELEASE)
2019-07-11 10:12:12.575 INFO 5872 --- [ main] com.shandesh.Application : Starting Application on SKD-PC with PID 5872 (G:\Shantanu\Learning\Technology\Projects\training\target\classes started by Shantanu in G:\Shantanu\Learning\Technology\Projects\training)
2019-07-11 10:12:12.582 INFO 5872 --- [ main] com.shandesh.Application : No active profile set, falling back to default profiles: default
2019-07-11 10:12:13.827 INFO 5872 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-11 10:12:13.925 INFO 5872 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 86ms. Found 1 repository interfaces.
2019-07-11 10:12:14.778 INFO 5872 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$bf78f5b2] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-07-11 10:12:15.211 INFO 5872 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-07-11 10:12:15.230 INFO 5872 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-07-11 10:12:15.231 INFO 5872 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/9.0.12
2019-07-11 10:12:15.238 INFO 5872 --- [ main] o.a.catalina.core.AprLifecycleListener : Loaded APR based Apache Tomcat Native library [1.2.21] using APR version [1.6.5].
2019-07-11 10:12:15.238 INFO 5872 --- [ main] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2019-07-11 10:12:15.238 INFO 5872 --- [ main] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2019-07-11 10:12:15.242 INFO 5872 --- [ main] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.1.1a 20 Nov 2018]
2019-07-11 10:12:15.396 INFO 5872 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-07-11 10:12:15.396 INFO 5872 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2735 ms
2019-07-11 10:12:15.434 INFO 5872 --- [ main] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2019-07-11 10:12:15.439 INFO 5872 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/]
2019-07-11 10:12:15.440 INFO 5872 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/]
2019-07-11 10:12:15.440 INFO 5872 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'formContentFilter' to: [/]
2019-07-11 10:12:15.440 INFO 5872 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/]
2019-07-11 10:12:15.481 WARN 5872 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
2019-07-11 10:12:15.484 INFO 5872 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-07-11 10:12:15.523 INFO 5872 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-07-11 10:12:15.531 ERROR 5872 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Process finished with exit code 1
I am hoping that this application would run successfully and I would be able to see JSON output of all user entries with https://localhost:8080/getAllUsers.
Change
findAppUserDTOSByUserName(String userName), findAppUserDTOSByUserId(Integer userId);
To
findByUserName(String userName), findByUserId(Integer userId);
The query builder mechanism built into Spring Data repository
infrastructure is useful for building constraining queries over
entities of the repository. The mechanism strips the prefixes find…By,
read…By, query…By, count…By, and get…By from the method and starts
parsing the rest of it. The introducing clause can contain further
expressions such as a Distinct to set a distinct flag on the query to
be created.
Also, note that you don't need to use #ResponseBody with #RestController as it is active by default. Change Return Type of getAllUsers() from Object to List<AppUserDTO>
I am learning Spring Boot for building Applications. I am trying to build my first Spring Boot Application with a controller in different package as application. Tomcat instance comes up but request does not reach RestController registered for the URI.
Following is the controller class:
package com.spring.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HelloController {
#RequestMapping(value = "/abc")
public String getHi() {
System.out.println("End Point hit");
return "Hi";
}
}
Following is the application class:
package com.spring.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(scanBasePackages = {"com.spring.controllers"})
public class SpringBootMain {
public static void main(String args[]) {
SpringApplication.run(SpringBootMain.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>RandomProjects</groupId>
<artifactId>SpringBoot</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<mainClass>com.spring.boot.SpringBootMain</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>
</dependencies>
Logs when tomcat starts:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.6.RELEASE)
2017-12-25 16:41:16.236 INFO 50314 --- [BootMain.main()] com.spring.boot.SpringBootMain : Starting SpringBootMain on f45c89be9049.ant.amazon.com with PID 50314 (/Users/sumt/Desktop/Work/RandomWork/RandomProjects/target/classes started by sumt in /Users/sumt/Desktop/Work/RandomWork/RandomProjects)
2017-12-25 16:41:16.244 INFO 50314 --- [BootMain.main()] com.spring.boot.SpringBootMain : No active profile set, falling back to default profiles: default
2017-12-25 16:41:16.408 INFO 50314 --- [BootMain.main()] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#7bbcce75: startup date [Mon Dec 25 16:41:16 IST 2017]; root of context hierarchy
2017-12-25 16:41:18.279 INFO 50314 --- [BootMain.main()] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-12-25 16:41:18.295 INFO 50314 --- [BootMain.main()] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-12-25 16:41:18.297 INFO 50314 --- [BootMain.main()] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-12-25 16:41:18.402 INFO 50314 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-12-25 16:41:18.402 INFO 50314 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2056 ms
2017-12-25 16:41:18.560 INFO 50314 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-12-25 16:41:18.564 INFO 50314 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-12-25 16:41:18.565 INFO 50314 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-12-25 16:41:18.565 INFO 50314 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-12-25 16:41:18.566 INFO 50314 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-12-25 16:41:18.920 INFO 50314 --- [BootMain.main()] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#7bbcce75: startup date [Mon Dec 25 16:41:16 IST 2017]; root of context hierarchy
2017-12-25 16:41:19.005 INFO 50314 --- [BootMain.main()] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-12-25 16:41:19.007 INFO 50314 --- [BootMain.main()] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-12-25 16:41:19.041 INFO 50314 --- [BootMain.main()] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-25 16:41:19.041 INFO 50314 --- [BootMain.main()] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-25 16:41:19.084 INFO 50314 --- [BootMain.main()] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-25 16:41:19.323 INFO 50314 --- [BootMain.main()] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-12-25 16:41:19.407 INFO 50314 --- [BootMain.main()] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-12-25 16:41:19.413 INFO 50314 --- [BootMain.main()] com.spring.boot.SpringBootMain : Started SpringBootMain in 3.889 seconds (JVM running for 6.196)
I have added base package scan and even tried with #ComponentScan annotation, but the result is same when I hit URL (http://localhost:8080/abc):
There was an unexpected error (type=Not Found, status=404).
No message available
Did anyone else face the same issue? Please suggest as how did you solve this.
Your Controller should be in the Child package of SpringBootApplication.
e.g if your SpringbootApplication main method is under com.text.demo package then your Controller class should be under com.text.demo.controller.
or add
#ComponentScan("com.text.demo.controller") on Spring boot Application main class.
As people mentioned in the comment try to add your base package.
#SpringBootApplication(scanBasePackages = {"com.spring"})
Or
#SpringBootApplication
#ComponentScan("com.spring")
But why don't you use this spring initializr https://start.spring.io/ to create a spring boot project from scratch. You can also add any dependency you need.
Here is the mini controller that I tried to reproduce from your example:
SpringApplication
package com.example.demo.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("com.example.demo.controller")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Controller
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HelloController {
#RequestMapping(value = "/abc")
public String getHi() {
System.out.println("End Point hit");
return "Hi";
}
}
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.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
and it works just fine!
As a suggestion, try calling default actuator endpoints e.g. http://localhost:8080/error. They come up with the Spring Boot and will show the actual status of your service.
Change your parent version number to below:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
The issue might be due to wrong import of #Service annotation. It should be a stereotype one.
Use this in your service class as usage of component scan in Springboot is not a better practice.
import org.springframework.stereotype.Service;
I'm using Spring and Spring Boot framework with Spring Security for a simple login projects with simple UI. In all my projects, using STS, after starting my application and run the localhost address without errors, i receive a popup login window and not my html page.
If i use user and default security password i always get a Whitelabel Error Page as results. Furthermore, if i use incorrect value the popup remain, if instead i use the default access value i get this message.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Aug 23 20:14:22 CEST 2017
There was an unexpected error (type=Not Found, status=404).
No message available
Here is a simple project code. All the html files are in template folder as you can see in project structure. I also try to use server.error.whitelabel.enabled=false in my application.properties file.`
Why has the html interface never been shown?
Project Structure
Application
package com.cyberdemon.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringbootUiLoginApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootUiLoginApplication.class, args);
}
}
SecurityConfig
package config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableAutoConfiguration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
#Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username,password, enabled from users where username=?")
.authoritiesByUsernameQuery("select username, role from user_roles where username=?");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home").permitAll().antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
.permitAll();
http.exceptionHandling().accessDeniedPage("/403");
}
}
WebController
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class WebController {
#RequestMapping(value = { "/", "home" })
public String home() {
return "home";
}
#RequestMapping(value = { "/welcome" })
public String welcome() {
return "welcome";
}
#RequestMapping(value = "/admin")
public String admin() {
return "admin";
}
#RequestMapping(value = { "/login" })
public String login() {
return "login";
}
#RequestMapping(value = "/403")
public String Error403() {
return "403";
}
}
Pom
<?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.cyberdemon.springboot</groupId>
<artifactId>springboot_UI_Login</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_UI_Login</name>
<description>Project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
properties
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=toor
Console
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.6.RELEASE)
2017-08-23 19:57:05.949 INFO 7496 --- [ main] c.c.s.SpringbootUiLoginApplication : Starting SpringbootUiLoginApplication on DESKTOP-CYBERDEMON with PID 7496 (started by GD in C:\Users\me\Documents\workspace-sts\springboot_ui_login)
2017-08-23 19:57:05.949 INFO 7496 --- [ main] c.c.s.SpringbootUiLoginApplication : No active profile set, falling back to default profiles: default
2017-08-23 19:57:06.121 INFO 7496 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#6cc7b4de: startup date [Wed Aug 23 19:57:06 CEST 2017]; root of context hierarchy
2017-08-23 19:57:07.293 INFO 7496 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-08-23 19:57:07.300 INFO 7496 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-08-23 19:57:07.300 INFO 7496 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-08-23 19:57:07.409 INFO 7496 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-08-23 19:57:07.409 INFO 7496 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1288 ms
2017-08-23 19:57:07.566 INFO 7496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-08-23 19:57:07.566 INFO 7496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-08-23 19:57:07.566 INFO 7496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-08-23 19:57:07.566 INFO 7496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-08-23 19:57:07.566 INFO 7496 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2017-08-23 19:57:07.566 INFO 7496 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-08-23 19:57:07.847 INFO 7496 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#6cc7b4de: startup date [Wed Aug 23 19:57:06 CEST 2017]; root of context hierarchy
2017-08-23 19:57:07.894 INFO 7496 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-08-23 19:57:07.894 INFO 7496 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-08-23 19:57:07.925 INFO 7496 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-23 19:57:07.925 INFO 7496 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-23 19:57:07.956 INFO 7496 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-23 19:57:08.519 INFO 7496 --- [ main] b.a.s.AuthenticationManagerConfiguration :
Using default security password: 21cf3953-b4e3-48ac-87fa-9041c41b3ff8
2017-08-23 19:57:08.567 INFO 7496 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2017-08-23 19:57:08.645 INFO 7496 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#12fcc71f, org.springframework.security.web.context.SecurityContextPersistenceFilter#5d43409a, org.springframework.security.web.header.HeaderWriterFilter#76563d26, org.springframework.security.web.authentication.logout.LogoutFilter#102ecc22, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#4eba373c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#6ede46f6, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#10a0fe30, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#5679e96b, org.springframework.security.web.session.SessionManagementFilter#23b8d9f3, org.springframework.security.web.access.ExceptionTranslationFilter#261ea657, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#6cd64ee8]
2017-08-23 19:57:08.864 INFO 7496 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-08-23 19:57:08.911 INFO 7496 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-08-23 19:57:08.926 INFO 7496 --- [ main] c.c.s.SpringbootUiLoginApplication : Started SpringbootUiLoginApplication in 3.164 seconds (JVM running for 3.428)
2017-08-23 19:57:24.008 INFO 7496 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-08-23 19:57:24.008 INFO 7496 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-08-23 19:57:24.021 INFO 7496 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 13 ms
You need to restructure your packages to that they fall under the package of your SpringbootUiLoginApplication or use #ComponentScan to tell the Spring Boot where to find your bean classes.
Following up on Ali's answer:
#SpringBootApplication implies #Configuration , #EnableAutoConfiguration and #ComponentScan
So, consider changing:
#Configuration
#EnableAutoConfiguration
public class SecurityConfig extends WebSecurityConfigurerAdapter
to:
#Component
public class SecurityConfig extends WebSecurityConfigurerAdapter
And to scan for beans in your entire package change:
#SpringBootApplication
public class SpringbootUiLoginApplication
to:
#SpringBootApplication
#ComponentScan("com.cyberdemon")
public class SpringbootUiLoginApplication
I got this when I didn't realize another Spring Boot application was running on port 8080. End that and you won't get that security modal.
I am using spring boot and MongoDB.
Spring version : 4.3.9
Spring boot version : 1.5.4
I am creating a repository which implements MongoRepository interface, like below
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface HotelRepository extends MongoRepository<Hotel,String> {
}
But, whenever I am adding a dependency to HotelRepository compiler giving the error Field hotelRepository in com.demo.HotelController required a bean of type 'com.demo.HotelRepository' that could not be found.
#RestController
#RequestMapping("/hotel")
public class HotelController {
#Autowired
private HotelRepository hotelRepository;
#GetMapping("/all")
public List<Hotel> getAllHotels(){
return this.hotelRepository.findAll();
}
}
I've examine all the aspects from my side to resolve the error but all in vain. What I've R&D.
For HotelRepository there will be a default implementation provided out of the box. as per spring docs
I've annotated the interface with #Repository, so no need to put #Component
Adding dependency from spring context using #Autowired annotation, So it should pick created bean from spring context.
All the required files are in the same package, so no need to put #ComponentScan
Here is my main spring boot application class :
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MongoWithBootApplication {
public static void main(String[] args) {
SpringApplication.run(MongoWithBootApplication.class, args);
}
}
application.properties :
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=HotelDB
Stack trace :
2017-07-10 13:25:12.485 INFO 4712 --- [ main] com.demo.MongoWithBootApplication : Starting MongoWithBootApplication on KELLGGNCPU0313 with PID 4712 (D:\STS_WS\MongoWithBoot\target\classes started by mehrajuddin.malik in D:\STS_WS\MongoWithBoot)
2017-07-10 13:25:12.487 INFO 4712 --- [ main] com.demo.MongoWithBootApplication : No active profile set, falling back to default profiles: default
2017-07-10 13:25:12.519 INFO 4712 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#13acb0d1: startup date [Mon Jul 10 13:25:12 IST 2017]; root of context hierarchy
2017-07-10 13:25:13.448 INFO 4712 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-07-10 13:25:13.456 INFO 4712 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-07-10 13:25:13.456 INFO 4712 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15
2017-07-10 13:25:13.541 INFO 4712 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-07-10 13:25:13.541 INFO 4712 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1025 ms
2017-07-10 13:25:13.635 INFO 4712 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-07-10 13:25:13.637 INFO 4712 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-07-10 13:25:13.638 INFO 4712 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-07-10 13:25:13.638 INFO 4712 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-07-10 13:25:13.638 INFO 4712 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-07-10 13:25:13.673 WARN 4712 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hotelController': Unsatisfied dependency expressed through field 'hotelRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.demo.HotelRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-07-10 13:25:13.675 INFO 4712 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2017-07-10 13:25:13.684 INFO 4712 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-07-10 13:25:13.737 ERROR 4712 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field hotelRepository in com.demo.HotelController required a bean of type 'com.demo.HotelRepository' that could not be found.
Action:
Consider defining a bean of type 'com.demo.HotelRepository' in your configuration.
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.demo</groupId>
<artifactId>MongoWithBoot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MongoWithBoot</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Could someone please help me out here what am I missing?
Faced similar problem, Adding the following to Application class helped me resolving the problem
#EnableMongoRepositories(basePackageClasses = DeviceDataRepository.class)
In your case it could be
#SpringBootApplication
#EnableMongoRepositories(basePackageClasses = HotelRepository.class)
public class MongoWithBootApplication{ ... }
I was facing the same problem
Used below code to scan mongorepository packages
#SpringBootApplication
#EnableMongoRepositories(basePackages = {"//packages you want to scan for activiting mongo repositories"})
public class SpringBootMongoDBApp{ ... }
It resolved my problem
we need to activate mongo repositories using EnableMongoRepositories
#SpringBootApplication
#EnableMongoRepositories //specify packages to scan
public class MongoWithBootApplication{ ... }
I have the same structure and I just had to add this configuration:
Application.java
#Configuration
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
...
}
application.properties
spring.data.mongodb.uri=mongodb://localhost:27017/hotelDB
And the repository package have to be in a deeper level of Application.java class. Thats all
com.hotelDB
Application.java
repository (Package)
controller (Package)
service (Package)
...
After so much of struggle, finally I've resolved the problem.
There is nothing wrong in the code or annotation. The problem was spring boot's version.
However, I am still not sure what is the wrong in the version above 1.5.1.RELEASE .If anybody knows the root cause can edit or answer the question.
Problem : If I add spring-boot-starter-parent above 1.5.1.RELEASE, it gives me the above no bean error for MongoRepository. It gives error from 1.5.2 to 1.5.4 version. (1.5.4 was the last version till that I've tried and faced the no bean error)
Solution : It runs fine if I add spring-boot-starter-parent 1.5.1.RELEASE or below (1.5.0 was lowest version till I've tried).
Just tried and did not found any problem at all with my existing spring boot mongodb project with 1.5.4.RELEASE for spring-boot-starter-parent.
Earlier it was configured with 1.4.0.RELEASE.