i am frustrated, Spring boot-hibernate is not a creating a table automatically for simplest program.
#Entity
#Table(name = "Question")
public class Question {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
String id;
String name;
// Default constructor
// Parametrized constrcutor
// Getters-Setters
}
Main file...
#SpringBootApplication
public class DbTestApplication {
public static void main(String[] args) {
SpringApplication.run(DbTestApplication.class, args);
}
}
Application.properties
# Datasource
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/test
spring.datasource.username=scott
spring.datasource.password=tiger
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
Console:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.4.RELEASE)
2017-06-24 23:58:05.497 INFO 4842 --- [ main] org.example.hotel.DbTestApplication : Starting DbTestApplication on PC192-168-2-107 with PID 4842 (/Users/bhalchandra/Documents/workspace-sts-3.8.3.RELEASE/DbTest/target/classes started by bhalchandra in /Users/bhalchandra/Documents/workspace-sts-3.8.3.RELEASE/DbTest)
2017-06-24 23:58:05.504 INFO 4842 --- [ main] org.example.hotel.DbTestApplication : No active profile set, falling back to default profiles: default
2017-06-24 23:58:05.571 INFO 4842 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#2f490758: startup date [Sat Jun 24 23:58:05 CEST 2017]; root of context hierarchy
2017-06-24 23:58:06.755 INFO 4842 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-06-24 23:58:06.778 INFO 4842 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-06-24 23:58:06.862 INFO 4842 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2017-06-24 23:58:06.864 INFO 4842 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-06-24 23:58:06.866 INFO 4842 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-06-24 23:58:06.914 INFO 4842 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-06-24 23:58:07.071 INFO 4842 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2017-06-24 23:58:07.446 INFO 4842 --- [ main] o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2017-06-24 23:58:07.448 INFO 4842 --- [ main] org.hibernate.type.BasicTypeRegistry : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#53b98ff6
2017-06-24 23:58:07.922 INFO 4842 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2017-06-24 23:58:07.936 INFO 4842 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-06-24 23:58:07.996 INFO 4842 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-06-24 23:58:08.364 INFO 4842 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-06-24 23:58:08.380 INFO 4842 --- [ main] org.example.hotel.DbTestApplication : Started DbTestApplication in 3.252 seconds (JVM running for 3.632)
2017-06-24 23:58:08.381 INFO 4842 --- [ Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#2f490758: startup date [Sat Jun 24 23:58:05 CEST 2017]; root of context hierarchy
2017-06-24 23:58:08.382 INFO 4842 --- [ Thread-3] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2017-06-24 23:58:08.383 INFO 4842 --- [ Thread-3] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-06-24 23:58:08.383 INFO 4842 --- [ Thread-3] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2017-06-24 23:58:08.386 INFO 4842 --- [ Thread-3] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc41</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
This is the simplest program i am trying to create a table using annotation. Finally, no table is created in database. Anybody can help me ?? It seems everything for me.
Seems like you need to enable EntityScan for Spring to find your model classes:
#SpringBootApplication
#EntityScan // <-- find all classes annotated with #Entity
public class DbTestApplication {
public static void main(String[] args) {
SpringApplication.run(DbTestApplication.class, args);
}
}
I found my mistake.
Question Entity is in package org.java.domain
DbTestApplication is in package org.java.dbtest
for spring boot, they must be either in the same package or in sub-package.
Related
I've created a new project with Spring Initializr and I configured connection with SSMS database:
spring.datasource.url=jdbc:sqlserver://xxxxxxxx;databaseName=yyyyyy
spring.datasource.username=
spring.datasource.password=
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto=update
I also created a test model class to check everything works fine:
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#EqualsAndHashCode(callSuper = false)
#ToString
#Builder
#Entity
#Table(name = "USR", schema = "dbo")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer usrId;
}
This is my console output:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.1)
2020-12-21 21:15:06.574 INFO 22192 --- [ restartedMain] c.e.employees.EmployeesApplication : Starting EmployeesApplication using Java 11.0.8 on DESKTOP-OEEHFPE with PID 22192 (C:\Alina\employees\target\classes started by olaru in C:\Alina\employees)
2020-12-21 21:15:06.577 INFO 22192 --- [ restartedMain] c.e.employees.EmployeesApplication : The following profiles are active: #spring.profiles.active#
2020-12-21 21:15:06.637 INFO 22192 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-12-21 21:15:07.211 INFO 22192 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-12-21 21:15:07.226 INFO 22192 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 5 ms. Found 0 JPA repository interfaces.
2020-12-21 21:15:07.646 INFO 22192 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-12-21 21:15:07.695 INFO 22192 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.25.Final
2020-12-21 21:15:07.798 INFO 22192 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2020-12-21 21:15:07.902 INFO 22192 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-12-21 21:15:08.200 INFO 22192 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-12-21 21:15:08.220 INFO 22192 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.SQLServer2012Dialect
2020-12-21 21:15:08.710 INFO 22192 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-12-21 21:15:08.721 INFO 22192 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-12-21 21:15:08.761 INFO 22192 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-12-21 21:15:08.873 INFO 22192 --- [ restartedMain] c.e.employees.EmployeesApplication : Started EmployeesApplication in 2.792 seconds (JVM running for 4.218)
2020-12-21 21:15:08.885 INFO 22192 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-12-21 21:15:08.892 INFO 22192 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-12-21 21:15:08.898 INFO 22192 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Process finished with exit code 0
I don't see any error in the console, but the table is not created. Please let me know if you have any idea what's wrong.
Did you add the required dependencies?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
</dependency>
You also need to enable entity scan, in case you didn't:
#Configuration
#EntityScan(basePackages = {"my.package"})
#EnableJpaRepositories(basePackages = {"my.package"})
Basically your first three properties would be enough, but the others shouldn't harm.
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=my-app
spring.datasource.username=sa
spring.datasource.password=<<YOUR_PASSWORD>>
If you like create a Spring Boot app for MS SQL at https://bootify.io to see the full configuration.
I have spring boot application previously I have used to in eclipse it works there, recently switched to IntelliJ, In IntelliJ application is not staring, here I am sharing logs while starting
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.RELEASE)
2019-09-20 13:34:56.609 INFO 30977 --- [ restartedMain] com.kn.Application : Starting Application on Dhanu-MAC.local with PID 30977 (/Applications/Data/RT/20190815_source_prod/2_etn_backend/target/classes started by dhanu in /Applications/Data/RT/20190815_source_prod/2_etn_backend)
2019-09-20 13:34:56.621 INFO 30977 --- [ restartedMain] com.kn.Application : The following profiles are active: dev
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/Users/dhanu/.m2/repository/org/codehaus/groovy/groovy/2.4.13/groovy-2.4.13.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2019-09-20 13:34:57.029 INFO 30977 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#5083ace5: startup date [Fri Sep 20 13:34:57 IST 2019]; root of context hierarchy
2019-09-20 13:35:04.145 INFO 30977 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/api] : Initializing Spring embedded WebApplicationContext
2019-09-20 13:35:04.146 INFO 30977 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 7117 ms
2019-09-20 13:35:04.798 INFO 30977 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-09-20 13:35:04.799 INFO 30977 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2019-09-20 13:35:04.801 INFO 30977 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'corsFilter' to: [/*]
2019-09-20 13:35:04.803 INFO 30977 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2019-09-20 13:35:05.107 INFO 30977 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-09-20 13:35:05.111 WARN 30977 --- [ restartedMain] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
2019-09-20 13:35:06.701 INFO 30977 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-09-20 13:35:07.535 INFO 30977 --- [ restartedMain] liquibase.database.core.OracleDatabase : Could not set remarks reporting on OracleDatabase: com.zaxxer.hikari.pool.HikariProxyConnection.setRemarksReporting(boolean)
2019-09-20 13:35:13.940 INFO 30977 --- [ restartedMain] l.lockservice.StandardLockService : Successfully released change log lock
2019-09-20 13:35:14.303 INFO 30977 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2019-09-20 13:35:18.144 INFO 30977 --- [ restartedMain] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2019-09-20 13:35:18.282 INFO 30977 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-09-20 13:35:20.040 WARN 30977 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jwtTokenProvider' defined in file [/Applications/Data/RT/20190815_source_prod/2_etn_backend/target/classes/com/kn/config/JwtTokenProvider.class]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlElement
2019-09-20 13:35:20.041 INFO 30977 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-09-20 13:35:20.045 INFO 30977 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2019-09-20 13:35:20.125 INFO 30977 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2019-09-20 13:35:20.131 INFO 30977 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
Process finished with exit code 0
As I see in logs it's successfully connected with DB, but tomcat stopped without showing any reason
I have stuck here for a long while, can someone help in this?
The nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlElement
the Question is answered here: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException in Java 9
in short: The required Dependency was removed from the JDK with the release of Java 9. If you start your application with a Java 8 JDK the dependency is provided and your application works. If you start your application with a Java 9 JDK or higher the dependency is no longer present and it fails to start.
The right solution to fix it would be to add the required dependencies to your project:
dependencies {
// JAX-B dependencies for JDK 9+
implementation "javax.xml.bind:jaxb-api:2.2.11"
implementation "com.sun.xml.bind:jaxb-core:2.2.11"
implementation "com.sun.xml.bind:jaxb-impl:2.2.11"
implementation "javax.activation:activation:1.1.1"
}
Maven dependencies
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-core -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.activation/activation -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
I've been trying to set up a rest service using spring data rest and spring boot. I followed the tutorial at https://spring.io/guides/gs/accessing-data-rest/ but the expected rest endpoints were not created on startup, and calling get methods on them only led to a 404. I can create an endpoint with RestController, but not with RepositoryRestResource. I am using Spring Boot 2 and hibernate 5.2, with postgres as the backing datastore. I am using eclipse, and have tried running the application via Run Java Application in eclipse, as well as running it from the windows command line using java -jar. The output and end result is the same. Does anybody know what I'm doing wrong and what I need to do for the expected endpoints to be created by the RepositoryRestResource? I've put example code below, with the spring boot output at the bottom, but first here are some similar questions and what I've tried:
this question has an accepted answer which seems to suggest its an entity scanning issue. However, I have added EntityScan to the Application and that didn't seem to help.
RepositoryRestResource with spring-boot CLI
this question has an answer suggesting wrapping the repository in a controller class with RestController instead of using RepositoryRestResource. I can do that, but I don't want to write all the extra code, I would rather that RepositoryRestResource work instead.
Clueless what I'm doing wrong setting up Spring Boot REST app
project structure:
pom.xml
src/main/java/com/springdataresttest/
Application.java
src/main/java/com/springdataresttest/entity/
Thing.java
src/main/java/com/springdataresttest/repository/
ThingRepository.java
src/main/resources/
application.properties
hibernate.properties
postgres ddl:
CREATE TABLE thing
(
id serial,
name varchar(255),
PRIMARY KEY (id)
)
pom.xml:
<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.springdataresttest</groupId>
<artifactId>springdataresttest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</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>
Application.java:
package com.springdataresttest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
#SpringBootApplication
#EntityScan(basePackages = {"com.springdataresttest.entity"})
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
Thing.java:
package com.springdataresttest.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "thing")
public class Thing {
private Integer id;
private String name;
#Id
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ThingRepository.java:
package com.springdataresttest.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.springdataresttest.entity.Thing;
#RepositoryRestResource(collectionResourceRel = "things", path = "things")
public interface ThingRepository extends PagingAndSortingRepository<Thing, Integer>{
}
application.properties:
security.basic.enabled=false
management.security.enabled=false
security.ignored=/**
spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/springdataresttest
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.username=postgres
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=none
spring.datasource.platform=POSTGRESQL
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.properties:
hibernate.connection.driver_class=org.postgresql.Driver
hibernate.connection.url=jdbc:postgresql://127.0.0.1:5432/springdataresttest
hibernate.connection.username=postgres
hibernate.connection.password=password
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.schema=public
output from spring boot (notice that rest repository endpoints for "things" are not mapped)
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.3.RELEASE)
2018-08-23 14:57:51.118 INFO 1336 --- [ main] com.springdataresttest.Application : Starting Application on LTW10me with PID 1336 (C:\Users\me.HQ\workspace\springdataresttest\target\classes started by me in C:\Users\me.HQ\workspace\springdataresttest)
2018-08-23 14:57:51.123 INFO 1336 --- [ main] com.springdataresttest.Application : No active profile set, falling back to default profiles: default
2018-08-23 14:57:51.233 INFO 1336 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#6646153: startup date [Thu Aug 23 14:57:51 EDT 2018]; root of context hierarchy
2018-08-23 14:57:52.882 INFO 1336 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$ca53dd09] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-08-23 14:57:53.548 INFO 1336 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-08-23 14:57:53.583 INFO 1336 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-08-23 14:57:53.583 INFO 1336 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-08-23 14:57:53.593 INFO 1336 --- [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_112\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_171/bin/server;C:/Program Files/Java/jre1.8.0_171/bin;C:/Program Files/Java/jre1.8.0_171/lib/amd64;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\PuTTY\;C:\Program Files\TortoiseSVN\bin;C:\Program Files (x86)\Bitvise SSH Client;C:\Program Files\TortoiseGit\bin;C:\Program Files\Git\cmd;C:\Program Files (x86)\Yarn\bin\;C:\Program Files\nodejs\;C:\WINDOWS\System32\OpenSSH\;"C:\Users\me.HQ\AppData\Local\Microsoft\WindowsApps;C:\Program Files (x86)\PuTTY;C:\Program Files\PostgreSQL\9.6\bin;C:\cygwin64;C;\cygwin64\bin;";C:\Users\me.HQ\AppData\Local\Microsoft\WindowsApps;;C:\Program Files\Microsoft VS Code\bin;C:\Users\me.HQ\AppData\Local\Yarn\bin;C:\Users\me.HQ\AppData\Roaming\npm;C:\eclipse;;.]
2018-08-23 14:57:53.709 INFO 1336 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-08-23 14:57:53.709 INFO 1336 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2481 ms
2018-08-23 14:57:53.876 INFO 1336 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-08-23 14:57:53.881 INFO 1336 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-08-23 14:57:53.881 INFO 1336 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-08-23 14:57:53.881 INFO 1336 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-08-23 14:57:53.886 INFO 1336 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-08-23 14:57:54.138 INFO 1336 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-08-23 14:57:54.720 INFO 1336 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-08-23 14:57:54.768 INFO 1336 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-08-23 14:57:54.793 INFO 1336 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-08-23 14:57:54.944 INFO 1336 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.2.17.Final}
2018-08-23 14:57:54.947 INFO 1336 --- [ main] org.hibernate.cfg.Environment : HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.username=postgres, hibernate.schema=public, hibernate.connection.password=****, hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect, hibernate.connection.url=jdbc:postgresql://127.0.0.1:5432/springdataresttest, hibernate.bytecode.use_reflection_optimizer=false, hibernate.connection.driver_class=org.postgresql.Driver}
2018-08-23 14:57:55.015 INFO 1336 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-08-23 14:57:55.155 WARN 1336 --- [ main] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000342: Could not obtain connection to query metadata : null
2018-08-23 14:57:55.168 INFO 1336 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2018-08-23 14:57:55.188 INFO 1336 --- [ main] o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000422: Disabling contextual LOB creation as connection was null
2018-08-23 14:57:55.193 INFO 1336 --- [ main] org.hibernate.type.BasicTypeRegistry : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#64f16277
2018-08-23 14:57:55.716 INFO 1336 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-08-23 14:57:55.851 INFO 1336 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-08-23 14:57:56.594 INFO 1336 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#6646153: startup date [Thu Aug 23 14:57:51 EDT 2018]; root of context hierarchy
2018-08-23 14:57:56.653 WARN 1336 --- [ 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
2018-08-23 14:57:56.698 INFO 1336 --- [ 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.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-08-23 14:57:56.703 INFO 1336 --- [ 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.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-08-23 14:57:56.748 INFO 1336 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-08-23 14:57:56.749 INFO 1336 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-08-23 14:57:57.112 INFO 1336 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-08-23 14:57:57.115 INFO 1336 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-08-23 14:57:57.120 INFO 1336 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-08-23 14:57:57.170 INFO 1336 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-08-23 14:57:57.180 INFO 1336 --- [ main] com.springdataresttest.Application : Started Application in 6.496 seconds (JVM running for 6.954)
I have initialed spring boot project using start.spring.io and added WEB,JPA,H2 dependencies.
Pom file
<?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.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<!-- <scope>runtime</scope> -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
application.properties
spring.h2.console.enabled=true
security.basic.enabled=false
DemoApplication.java
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
UserController.java
#RestController
public class UserController {
#GetMapping("/hello")
public String hello() {
return "Hello";
}
Console Log
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.10.RELEASE)
2018-02-26 11:24:28.846 INFO 4792 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication on RAJAT-PC with PID 4792 (C:\Users\devra\Downloads\Compressed\demo\target\classes started by rajat in C:\Users\devra\Downloads\Compressed\demo)
2018-02-26 11:24:28.855 INFO 4792 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2018-02-26 11:24:29.018 INFO 4792 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#6b67034: startup date [Mon Feb 26 11:24:29 IST 2018]; root of context hierarchy
2018-02-26 11:24:30.894 INFO 4792 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$fa7e8c5a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-02-26 11:24:31.720 INFO 4792 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-02-26 11:24:31.737 INFO 4792 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-02-26 11:24:31.740 INFO 4792 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-02-26 11:24:31.969 INFO 4792 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-02-26 11:24:31.970 INFO 4792 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2957 ms
2018-02-26 11:24:32.307 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-26 11:24:32.308 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-02-26 11:24:32.309 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-02-26 11:24:32.309 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-02-26 11:24:32.310 INFO 4792 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-02-26 11:24:32.311 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-02-26 11:24:32.313 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'webServlet' to [/h2-console/*]
2018-02-26 11:24:33.004 INFO 4792 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-02-26 11:24:33.038 INFO 4792 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-02-26 11:24:33.196 INFO 4792 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2018-02-26 11:24:33.199 INFO 4792 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-02-26 11:24:33.202 INFO 4792 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2018-02-26 11:24:33.266 INFO 4792 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-02-26 11:24:33.517 INFO 4792 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2018-02-26 11:24:33.807 INFO 4792 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2018-02-26 11:24:33.816 INFO 4792 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2018-02-26 11:24:33.859 INFO 4792 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-02-26 11:24:34.365 INFO 4792 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#6b67034: startup date [Mon Feb 26 11:24:29 IST 2018]; root of context hierarchy
2018-02-26 11:24:34.506 INFO 4792 --- [ 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)
2018-02-26 11:24:34.508 INFO 4792 --- [ 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)
2018-02-26 11:24:34.568 INFO 4792 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:34.569 INFO 4792 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:34.663 INFO 4792 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:35.147 INFO 4792 --- [ main] b.a.s.AuthenticationManagerConfiguration :
Using default security password: dd5212d7-4de1-4fee-9f6b-f5cd888f2f17
2018-02-26 11:24:35.222 INFO 4792 --- [ 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']]], []
2018-02-26 11:24:35.334 INFO 4792 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$ApplicationNoWebSecurityConfigurerAdapter$1#11c713b7, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#2251b3bc, org.springframework.security.web.context.SecurityContextPersistenceFilter#602f8f94, org.springframework.security.web.header.HeaderWriterFilter#2785db06, org.springframework.security.web.csrf.CsrfFilter#603cabc4, org.springframework.security.web.authentication.logout.LogoutFilter#7a9ceddf, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#4dfe8b37, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#7e64c1a9, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#3fbe503c, org.springframework.security.web.session.SessionManagementFilter#715a70e9, org.springframework.security.web.access.ExceptionTranslationFilter#1cc8416a]
2018-02-26 11:24:35.552 INFO 4792 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-02-26 11:24:35.652 INFO 4792 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-02-26 11:24:35.670 INFO 4792 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 7.302 seconds (JVM running for 7.824)
as you can see spring didn't mapped the /hello url
Considering that the other answers don't explain why it doesn't work as expected, here's why.
Spring uses component scanning to find eligible beans (#Repository, #Service, #Component, #Controller, ...). This is usually done by using the #ComponentScan annotation.
This is explained in the core docs:
To autodetect these classes and register the corresponding beans, you need to add #ComponentScan to your #Configuration class, where the basePackages attribute is a common parent package for the two classes. (Alternatively, you can specify a comma/semicolon/space-separated list that includes the parent package of each class.)
Spring Boot, by default only scans components within the same package (and including subpackages) of the main class. This is because the #SpringBootApplication annotation includes a #ComponentScanby default, as mentioned in the Spring boot docs:
The #SpringBootApplication annotation is equivalent to using #Configuration, #EnableAutoConfiguration and #ComponentScan with their default attributes
If you want Spring to automatically detect your controller, you have three options:
Move the controller to the com.example.demo package. This is the recommended approach according to the Spring boot documentation.
Telling Spring to look at the controller package by adding a #ComponentScan annotation:
#SpringBootApplication
#ComponentScan({"com.example.demo", "controller"}) // Add this
public class DemoApplication {
// ...
}
Telling Spring to look at the controller package by configuring the scanBasePackages property of #SpringBootApplication:
#SpringBootApplication(scanBasePackages = {"com.example.demo", "controller"}) // Add this
public class DemoApplication {
// ...
}
Spring reference doc says - Generally recommend that you locate your main application class in a root package above other classes like
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
For more refer this link :
https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html
I am studying Spring Mvc and Spring Boot and came across the following problem that until now could not identify. After running my main method I get the following message.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback. Tue Jul 20 21:22:43 BRT 2016 There was an unexpected error (type=Not Found, status=404). No message available
Controller
#Controller
#RequestMapping(value="/restauranteWeb")
public class HomeController {
#RequestMapping(method=RequestMethod.GET)
public String redirect() {
return "login/login";
}
}
Method Main
#SpringBootApplication()
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Configuration
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.gervasios.rsw")
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
registry.viewResolver(viewResolver);
}
}
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer tilesConfigurer = new TilesConfigurer();
tilesConfigurer.setDefinitions(new String[] {"/**/WEB-INF/**/tiles-config.xml"});
tilesConfigurer.setCheckRefresh(true);
return tilesConfigurer;
}
AppInitializer
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {ApplicationConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[0];
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
POM
<!-- Spring BOOT-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.2.5.RELEASE</spring.version>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Javax - Jsf -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
LOG localhost:8080/restauranteWeb
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.5.RELEASE)
2016-07-21 22:24:17.632 INFO 4576 --- [ main] c.g.r.configuration.ApplicationExecute : Starting ApplicationExecute on Helio-PC with PID 4576 (C:\Users\Helio\git\restauranteWeb\restauranteWeb\target\classes started by Helio in C:\Users\Helio\git\restauranteWeb\restauranteWeb)
2016-07-21 22:24:17.632 INFO 4576 --- [ main] c.g.r.configuration.ApplicationExecute : No active profile set, falling back to default profiles: default
2016-07-21 22:24:17.695 INFO 4576 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#1f32bf7: startup date [Thu Jul 21 22:24:17 BRT 2016]; root of context hierarchy
2016-07-21 22:24:19.433 INFO 4576 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$1e356ee6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-07-21 22:24:20.124 INFO 4576 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-07-21 22:24:20.139 INFO 4576 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-07-21 22:24:20.155 INFO 4576 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.33
2016-07-21 22:24:20.358 INFO 4576 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-07-21 22:24:20.358 INFO 4576 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2663 ms
2016-07-21 22:24:20.514 INFO 4576 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-07-21 22:24:20.530 INFO 4576 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-07-21 22:24:20.612 INFO 4576 --- [ main] o.s.j.d.DriverManagerDataSource : Loaded JDBC driver: com.mysql.jdbc.Driver
2016-07-21 22:24:21.020 INFO 4576 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2016-07-21 22:24:21.036 INFO 4576 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2016-07-21 22:24:21.129 INFO 4576 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {4.3.11.Final}
2016-07-21 22:24:21.129 INFO 4576 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2016-07-21 22:24:21.129 INFO 4576 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2016-07-21 22:24:21.348 INFO 4576 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2016-07-21 22:24:21.426 INFO 4576 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2016-07-21 22:24:21.489 INFO 4576 --- [ main] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory
2016-07-21 22:24:21.801 INFO 4576 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2016-07-21 22:24:21.913 INFO 4576 --- [ main] o.h.e.t.i.TransactionFactoryInitiator : HHH000399: Using default transaction strategy (direct JDBC transactions)
2016-07-21 22:24:21.913 INFO 4576 --- [ main] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory
2016-07-21 22:24:22.100 INFO 4576 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2016-07-21 22:24:22.100 INFO 4576 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000102: Fetching database metadata
2016-07-21 22:24:22.116 INFO 4576 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000396: Updating schema
2016-07-21 22:24:22.116 INFO 4576 --- [ main] java.sql.DatabaseMetaData : HHH000262: Table not found: RESADM.TUSUARIO
2016-07-21 22:24:22.116 INFO 4576 --- [ main] java.sql.DatabaseMetaData : HHH000262: Table not found: RESADM.TUSUARIO
2016-07-21 22:24:22.116 INFO 4576 --- [ main] java.sql.DatabaseMetaData : HHH000262: Table not found: RESADM.TUSUARIO
2016-07-21 22:24:22.131 ERROR 4576 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000388: Unsuccessful: create table RESADM.TUSUARIO (CODUSUARIO bigint not null auto_increment, DATCAD datetime, LOGIN varchar(255), SENHA varchar(255), SITUACAO varchar(255), primary key (CODUSUARIO))
2016-07-21 22:24:22.131 ERROR 4576 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : Table 'tusuario' already exists
2016-07-21 22:24:22.131 INFO 4576 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000232: Schema update complete
2016-07-21 22:24:22.392 INFO 4576 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/restauranteWeb],methods=[GET]}" onto public java.lang.String com.gervasios.rsw.controller.HomeController.redirect()
2016-07-21 22:24:22.408 INFO 4576 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/principal],methods=[GET]}" onto public java.lang.String com.gervasios.rsw.controller.PrincipalController.principal()
2016-07-21 22:24:22.408 INFO 4576 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/cadastroUsuario],methods=[GET]}" onto public java.lang.String com.gervasios.rsw.controller.UsuarioController.newUser(org.springframework.ui.Model)
2016-07-21 22:24:22.408 INFO 4576 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/cadastrarUsuario],methods=[POST]}" onto public java.lang.String com.gervasios.rsw.controller.UsuarioController.salvar(com.gervasios.rsw.model.Usuario,org.springframework.ui.ModelMap)
2016-07-21 22:24:22.408 INFO 4576 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/usuariosSearch],methods=[GET]}" onto public void com.gervasios.rsw.controller.UsuarioController.buscarUsuarios(org.springframework.ui.Model)
2016-07-21 22:24:22.408 INFO 4576 --- [ 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)
2016-07-21 22:24:22.408 INFO 4576 --- [ 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)
2016-07-21 22:24:22.439 INFO 4576 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/resources/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-07-21 22:24:22.533 INFO 4576 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#1f32bf7: startup date [Thu Jul 21 22:24:17 BRT 2016]; root of context hierarchy
2016-07-21 22:24:22.611 INFO 4576 --- [ main] o.s.o.h.HibernateTransactionManager : Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource#1edc703] of Hibernate SessionFactory for HibernateTransactionManager
2016-07-21 22:24:23.048 INFO 4576 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-07-21 22:24:23.159 INFO 4576 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-07-21 22:24:23.159 INFO 4576 --- [ main] c.g.r.configuration.ApplicationExecute : Started ApplicationExecute in 5.949 seconds (JVM running for 6.325)
2016-07-21 22:24:54.039 INFO 4576 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-07-21 22:24:54.039 INFO 4576 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2016-07-21 22:24:54.073 INFO 4576 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 34 ms
2016-07-21 22:24:54.198 WARN 4576 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/WEB-INF/pages/login/login.jsp] in DispatcherServlet with name 'dispatcherServlet'