My application runs but nothing about mapping is shown in console. My Application class file is above controller and also added #ComponentScan(basePackages : "com.org.name.controller") to scan for controllers. Still no mapping shows up in console. I have commented out #Autowired in controller class as i was getting error of :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-07-12 11:05:16.014 ERROR 14104 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userService in com.homzhub.lms.controller.UserController required a bean of type 'com.homzhub.lms.service.UserService' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.homzhub.lms.service.UserService' in your configuration.
Main class:
package com.homzhub.lms;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages = {"com.homzhub.lms.controller"})
//#EnableJpaRepositories("repository")
//#EnableAutoConfiguration
public class LmsApplication{
public static void main(String[] args){
SpringApplication.run(LmsApplication.class, args);
}
}
appointment controller :
package com.homzhub.lms.controller;
import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.homzhub.lms.entity.Appointment;
import com.homzhub.lms.entity.User;
import com.homzhub.lms.service.AppointmentService;
import com.homzhub.lms.service.UserService;
#Controller
#RequestMapping(path = "/appointment")
public class AppointmentController {
// #Autowired
private AppointmentService appointmentService;
//#Autowired
private UserService userService;
#RequestMapping(value = "/create", method = RequestMethod.GET)
public void createAppointment(Model model) {
Appointment appointment = new Appointment();
model.addAttribute("appointment", appointment);
model.addAttribute("dateString", "");
}
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String createAppointmentPost(#ModelAttribute("appointment") Appointment appointment, #ModelAttribute("dateString") String date, Model model, Principal principal) throws ParseException {
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date d1 = format1.parse(date);
appointment.setDate(d1);
User user = userService.findByUsername(principal.getName());
appointment.setUser(user);
appointmentService.createAppointment(appointment);
return "redirect:/userFront";
}
}
pom.xml 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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<!-- <version>1.5.21.RELEASE</version> -->
<version>2.1.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.homzhub</groupId>
<artifactId>lms</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>lms</name>
<description>Lead Management System</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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-thymeleaf</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Console output. After commenting out #Autowired in controller classes the application runs but no mapping is done :
2019-07-12 12:58:04.638 INFO 18828 --- [ main] com.homzhub.lms.LmsApplication : Starting LmsApplication v0.0.1-SNAPSHOT on rms-Lenovo-ideapad-330-15IKB with PID 18828 (/home/rms/lms/target/lms-0.0.1-SNAPSHOT.jar started by rms in /home/rms/lms)
2019-07-12 12:58:04.644 INFO 18828 --- [ main] com.homzhub.lms.LmsApplication : No active profile set, falling back to default profiles: default
2019-07-12 12:58:05.941 INFO 18828 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-12 12:58:06.161 INFO 18828 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 204ms. Found 13 repository interfaces.
2019-07-12 12:58:06.849 INFO 18828 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d931452d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-07-12 12:58:07.301 INFO 18828 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-07-12 12:58:07.350 INFO 18828 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-07-12 12:58:07.350 INFO 18828 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-07-12 12:58:07.484 INFO 18828 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-07-12 12:58:07.484 INFO 18828 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2751 ms
2019-07-12 12:58:07.952 INFO 18828 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-07-12 12:58:08.286 INFO 18828 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-07-12 12:58:08.388 INFO 18828 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-07-12 12:58:08.519 INFO 18828 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.10.Final}
2019-07-12 12:58:08.521 INFO 18828 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-07-12 12:58:08.773 INFO 18828 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-07-12 12:58:09.175 INFO 18828 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-07-12 12:58:10.967 INFO 18828 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-07-12 12:58:12.284 INFO 18828 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-12 12:58:12.364 WARN 18828 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-07-12 12:58:12.923 INFO 18828 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2019-07-12 12:58:13.211 INFO 18828 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: f1e93a8f-d01a-4050-8724-87ff348fab02
2019-07-12 12:58:13.388 INFO 18828 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#1dcca8d3, org.springframework.security.web.context.SecurityContextPersistenceFilter#6daf2337, org.springframework.security.web.header.HeaderWriterFilter#70e3f36f, org.springframework.security.web.csrf.CsrfFilter#3c7cfcbb, org.springframework.security.web.authentication.logout.LogoutFilter#7d755813, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#4e25147a, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#60e5272, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#5631962, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#56303475, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#250b236d, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#432034a, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#52a70627, org.springframework.security.web.session.SessionManagementFilter#23e44287, org.springframework.security.web.access.ExceptionTranslationFilter#1bfe3203, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#71870da7]
2019-07-12 12:58:13.517 INFO 18828 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-07-12 12:58:13.520 INFO 18828 --- [ main] com.homzhub.lms.LmsApplication : Started LmsApplication in 9.518 seconds (JVM running for 10.158)
UserService class :
package com.homzhub.lms.service;
import java.util.List;
import java.util.Set;
import org.springframework.stereotype.Service;
import com.homzhub.lms.entity.User;
import com.homzhub.lms.security.UserRole;
//#Service("userDetailsService")
#Service
public interface UserService{
User findByUsername(String username);
User findByEmail(String email);
// User findByPhoneNumber(String phoneNumber);
boolean checkUserExists(String username, String email);
boolean checkUsernameExists(String username);
boolean checkEmailExists(String email);
void save(User user);
User createUser(User user, Set<UserRole> userRoles);
User saveUser(User user);
List<User> findUserList();
void enableUser(String username);
void disableUser(String username);
}
If it isn't already, you need to define UserService as a Component, or more appropriately as a Service. If it already is you have to map it, which is a bit weird considering Spring should do that on its own.
Your are only scanning com.homzhub.lms.controller and UserService is not under ComponentScan.
You need to add service package to ComponentScan
#ComponentScan(basePackages = {"com.homzhub.lms"})
You service is under com.homzhub.lms.service package so you have to add this package to #ComponentScan too, so Spring will scan this package too and pick up the classes marked with stereotypes there :
#SpringBootApplication
#ComponentScan(basePackages = {"com.homzhub.lms.controller, "com.homzhub.lms.service"})
public class LmsApplication{
public static void main(String[] args){
SpringApplication.run(LmsApplication.class, args);
}
}
However I can see that your class annotated with #SpringBootApplication is already above all the packages with your components so you could get rid of #ComponentScan annotation at all. So it will scan nested packages by default.
And also remember about annotating your service classes with Spring stereotypes annotations for example #Service so component scan will be able to pick them up.
Uncomment #Autowired annotation. Put #Service annotation on the implementing class instead of the interface and make sure your implementing class is discover-able via componentScan. Also, as a side note, Spring will scan all subpackages of your main class (class with #SpringBootApplication annotation). So it would be a good idea to have a directory structure like com.homzhub.lms as a root and com.homzhub.lms.controller for controllers com.homzhub.lms.service for service and com.homzhub.lms.service.impl if you want to keep implementations in a different package. If you are following this structure, you won't need componentScan.
Related
im building CRUD app but ran into a problem . When I start the application at http://localhost:8080/api/v1/employees i recieve a whitelabel error 404 instead JSON response with db data .
Message
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Sep 08 17:49:26 GST 2022
There was an unexpected error (type=Not Found, status=404).
No message available
Controller
package com.crudpet.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.crudpet.model.Employee;
import com.crudpet.repository.EmployeeRepository;
#RestController
#RequestMapping("/api/v1/")
public class EmployeeController {
#Autowired
private EmployeeRepository employeeRepository;
#GetMapping("/employees")
public List<Employee> getAllEmployees(){
return employeeRepository.findAll();
}
}
main class
package com.crudpet.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class SpringbootBackendCrudApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootBackendCrudApplication.class, args);
}
}
console
2022-09-08 17:49:19.486 INFO 836 --- [ restartedMain] c.c.s.SpringbootBackendCrudApplication : Starting SpringbootBackendCrudApplication using Java 17.0.1 on DESKTOP-08M3S29 with PID 836 (C:\Users\Bogich\Documents\workspace-spring-tool-suite-4-4.13.1.RELEASE\springboot-backend-crud\target\classes started by Bogich in C:\Users\Bogich\Documents\workspace-spring-tool-suite-4-4.13.1.RELEASE\springboot-backend-crud)
2022-09-08 17:49:19.487 INFO 836 --- [ restartedMain] c.c.s.SpringbootBackendCrudApplication : No active profile set, falling back to 1 default profile: "default"
2022-09-08 17:49:19.556 INFO 836 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-09-08 17:49:19.556 INFO 836 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-09-08 17:49:20.206 INFO 836 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-09-08 17:49:20.223 INFO 836 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 7 ms. Found 0 JPA repository interfaces.
2022-09-08 17:49:20.833 INFO 836 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-09-08 17:49:20.844 INFO 836 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-09-08 17:49:20.844 INFO 836 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-09-08 17:49:20.917 INFO 836 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-09-08 17:49:20.917 INFO 836 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1360 ms
2022-09-08 17:49:21.132 INFO 836 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-09-08 17:49:21.193 INFO 836 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.10.Final
2022-09-08 17:49:21.388 INFO 836 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-09-08 17:49:21.507 INFO 836 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-09-08 17:49:21.684 INFO 836 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-09-08 17:49:21.701 INFO 836 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2022-09-08 17:49:21.988 INFO 836 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-09-08 17:49:21.999 INFO 836 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-09-08 17:49:22.063 WARN 836 --- [ restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-09-08 17:49:22.450 INFO 836 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2022-09-08 17:49:22.492 INFO 836 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-09-08 17:49:22.502 INFO 836 --- [ restartedMain] c.c.s.SpringbootBackendCrudApplication : Started SpringbootBackendCrudApplication in 3.407 seconds (JVM running for 4.229)
2022-09-08 17:49:26.819 INFO 836 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-09-08 17:49:26.819 INFO 836 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-09-08 17:49:26.820 INFO 836 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.crudpet</groupId>
<artifactId>springboot-backend-crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-backend-crud</name>
<description>Demo project for Spring Boot</description>
<properties>
<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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The problem is when i start app i must recieve a JSON response but i see Whitelabel error.
I've tried ComponentScan , but it is not work for me.
What i must do?
You haven't specified the package name in your controller and main classes.
The default Spring auto-discovery won't work because of this, and your controller won't be instantiated. Spring looks for the components under the packages specified classes. Without the specified package, Spring won't be able to 'see' your beans and add them to ApplicationContext.
Simply add the package statement at the top of your class and everything should start working correctly.
Example:
package com.example;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.crudpet.model.Employee;
import com.crudpet.repository.EmployeeRepository;
#RestController
#RequestMapping("/api/v1/")
public class EmployeeController {
#Autowired
private EmployeeRepository employeeRepository;
#GetMapping("/employees")
public List<Employee> getAllEmployees(){
return employeeRepository.findAll();
}
}
Updated:
Your main class SpringbootBackendCrudApplication, which is marked as #SpringBootApplication is located in the package com.crudpet.springboot. Whereas your controller is located in the com.crudpet.controller package.
By default, Spring Boot will scan for beans in the base package of the class with main method (SpringbootBackendCrudApplication in your case) and all nested packages (e.g., com.crudpet.springboot.example). The com.crudpet.controller package with your controller class is out of scope and simply wasn't initiated.
To fix this, you need to place the SpringbootBackendCrudApplication class in the com.crudpet package, which is best practice. Another possible solution is explicitly specifying the com.crudpet.controller package in the component scan.
I tried to test Spring Boot with MongoDB but when I run mvn, the server run just fine but can't find the mapping in the RestController
#RestController
#RequestMapping("/mongotest")
public class UserController {
#Autowired
private UserService service;
#RequestMapping(value = "/getallusers" , method = RequestMethod.GET)
public List<User> getAllUser(){
return service.findAll();
}
#RequestMapping(value = "/saveuser" , method = RequestMethod.POST)
public void saveUser(#RequestBody User user){
service.createUser(user);
}
#GetMapping(value = "/hello")
public String test(){
return "hello world";
}
}
#Repository
public interface UserDAO extends MongoRepository<User,String>{
List<User> findByName(String name);
List<User> findByDepartment(String department);
}
#Entity
#Getter #Setter #NoArgsConstructor #ToString #AllArgsConstructor
#Document(collection = "users")
public class User{
#Id
private Long id;
#Field(value = "name")
private String name;
#Field(value = "age")
private Integer age;
#Field(value = "department")
private String department;
}
spring.data.mongodb.database= test_mongo
#SpringBootApplication
#EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("Deploy successful");
}
}
Update the service class
#Service
public class UserService{
#Autowired
private UserDAO userDAO;
public User createUser(User u){
return userDAO.save(u);
}
public List<User> findByName(String name){
return userDAO.findByName(name);
}
public List<User> findByDepartment(String department){
return userDAO.findByDepartment(department);
}
public List<User> findAll(){
return userDAO.findAll();
}
}
Update 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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.demo</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<scope>provided</scope>
</dependency>
<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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The program run just fine but in the log can't find the part mapping with the RequestMapping i have in the UserController
And when i run the mapped link return 404
```Project struct
src
main
java
com
example
demo
controller
UserController.java
demo
DemoApplication.java
entity
User.java
repository
UserDAO.java
service
UserService.java
resources
application.properties
pom.xml
2019-09-09 22:42:05.856 INFO 19036 --- [ main] com.example.demo.demo.DemoApplication : Starting DemoApplication on DESKTOP-UNR6TSG with PID 19036 (E:\demo\target\classes started by MemeLord in E:\demo)
2019-09-09 22:42:05.861 INFO 19036 --- [ main] com.example.demo.demo.DemoApplication : No active profile set, falling back to default profiles: default
2019-09-09 22:42:06.782 INFO 19036 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2019-09-09 22:42:06.784 INFO 19036 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-09-09 22:42:06.806 INFO 19036 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 17ms. Found 0 repository interfaces.
2019-09-09 22:42:07.549 INFO 19036 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-09-09 22:42:07.588 INFO 19036 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-09-09 22:42:07.588 INFO 19036 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.24]
2019-09-09 22:42:07.707 INFO 19036 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-09-09 22:42:07.708 INFO 19036 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1790 ms
2019-09-09 22:42:08.053 INFO 19036 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-09 22:42:09.060 INFO 19036 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-09-09 22:42:09.138 INFO 19036 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:2}]
to localhost:27017
2019-09-09 22:42:09.144 INFO 19036 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2, 0]}, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=3475900}
2019-09-09 22:42:09.401 INFO 19036 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-09-09 22:42:09.404 INFO 19036 --- [ main] com.example.demo.demo.DemoApplication : Started DemoApplication in 4.07 seconds (JVM running for 8.531)
Deploy successful
Your packages have the wrong structure. You have to put them into your second demo, where your DemoApplicationis, not the first as you did. Then Spring will recognize them.
Here you can read about the package structuring in Spring Boot.
Please provide your package structure
You either need to have all your controller as a sub-packages from class where is your main method lives or use #ComponentScan annotation. I prefer the second way and highly recommend it to you
I am creating a simple Spring Boot application with JpaRepository, but when I am trying to run my application it gives an error that "NoSuchBeanDefinitionException". I am new to Spring Boot.
I have also tried to annotate my main class with #SpringBootApplication
#EnableJpaRepositories("com.ab.repository") annotations but whenever I am trying to annotate #EnableJpaRepository(), it is showing error in STS that
The type org.springframework.data.repository.config.BootstrapMode cannot be resolved. It is indirectly referenced from required .class files.
Previously I was not using this annotation but I saw in a question that I have to tell my class to enable JPA repository, so I tried this as well, but it is also not working.
My main class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootMain {
public static void main(String[] args) {
SpringApplication.run(SpringBootMain.class, args);
}
}
Controller Class is :
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ab.model.WebServiceModel;
import com.ab.service.WebSrvService;
#RestController
public class WebServiceController {
#Autowired
private WebSrvService webSrvService;
#PostMapping(value = "/save")
public void saveRecord(#RequestBody WebServiceModel webServiceModel) {
webSrvService.saveRecord(webServiceModel);
}
}
Service class:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ab.model.WebServiceModel;
import com.ab.repository.WebServiceRepository;
#Service
public class WebSrvService {
#Autowired
private WebServiceRepository webServiceRepository;
public void saveRecord(WebServiceModel webServiceModel) {
webServiceRepository.save(webServiceModel);
}
}
Repository Interface:
import org.springframework.data.jpa.repository.JpaRepository;
import com.ab.model.WebServiceModel;
public interface WebServiceRepository extends JpaRepository<WebServiceModel, Integer> {
}
and my pom.xml file is:
<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.ab</groupId>
<artifactId>SpringBootTry</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.1.10.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
</dependencies>
</project>
Please correct me what I am doing wrong, I am Expecting it to run properly but I am getting an error message:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ab.repository.WebServiceRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
After looking through your code that you posted on github i pulled it and rightfully so you have problems with your dependencies. You where missing the spring build plugin that includes all the dependencies in the jar.
Always use the Spring initlizr when starting a new project and it will set up all this for you automatically (unless you have good experience with spring and know what you are doing).
fully working 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.ab</groupId>
<artifactId>SpringBootTry</artifactId>
<version>0.0.1-SNAPSHOT</version>
// latest version of spring as of writing 2.1.7
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
</parent>
// set what version you want of java 1.8, 9, 10, 11, 12?
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
// You need the spring plugin to bild a fat jar that includes all
// the dependencies. Without this, no dependencies are included in
// the jar and you get NoSuchBeanDefinitionexception
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
you also need to update your application properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
or else you will get a warning when you start your server.
Remove “#Repository”, maybe you can
I created both the folder structure and code like yours.
package com.ab;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootTry1Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootTry1Application.class, args);
}
}
Why you change your main class name?Spring boot automatically create main class for you.
package com.ab.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.ab.model.WebServiceModel;
import com.ab.service.WebService;
#Controller
public class WebServiceController {
#Autowired
private WebService webSrvService;
#PostMapping(value = "/save")
public void saveRecord(#RequestBody WebServiceModel webServiceModel) {
webSrvService.saveRecord(webServiceModel);
}
}
package com.ab.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ab.model.WebServiceModel;
import com.ab.repository.WebServiceRepository;
#Service
public class WebService {
#Autowired
private WebServiceRepository webServiceRepository;
public void saveRecord(WebServiceModel webServiceModel) {
webServiceRepository.save(webServiceModel);
}
}
package com.ab.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.ab.model.WebServiceModel;
public interface WebServiceRepository extends JpaRepository<WebServiceModel,Integer>{
}
## LOGS ##
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.7.RELEASE)
2019-09-01 18:26:27.412 INFO 5522 --- [ main] com.ab.SpringBootTry1Application : Starting SpringBootTry1Application on BGINMAC004.local with PID 5522 (/Users/Dildeep.Singh/Documents/workspace-sts-3.9.9.RELEASE/SpringBootTry-1/target/classes started by Dildeep.Singh in /Users/Dildeep.Singh/Documents/workspace-sts-3.9.9.RELEASE/SpringBootTry-1)
2019-09-01 18:26:27.414 INFO 5522 --- [ main] com.ab.SpringBootTry1Application : No active profile set, falling back to default profiles: default
2019-09-01 18:26:27.992 INFO 5522 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-09-01 18:26:28.055 INFO 5522 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 57ms. Found 1 repository interfaces.
2019-09-01 18:26:28.354 INFO 5522 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$8d03f4e2] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-09-01 18:26:28.583 INFO 5522 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-09-01 18:26:28.602 INFO 5522 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-09-01 18:26:28.603 INFO 5522 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.22]
2019-09-01 18:26:28.692 INFO 5522 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-09-01 18:26:28.692 INFO 5522 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1250 ms
2019-09-01 18:26:28.839 INFO 5522 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-09-01 18:26:28.937 INFO 5522 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-09-01 18:26:28.981 INFO 5522 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-09-01 18:26:29.141 INFO 5522 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.10.Final}
2019-09-01 18:26:29.142 INFO 5522 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-09-01 18:26:29.228 INFO 5522 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-09-01 18:26:29.316 INFO 5522 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2019-09-01 18:26:29.743 INFO 5522 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#3850e90c'
2019-09-01 18:26:29.746 INFO 5522 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-09-01 18:26:30.149 INFO 5522 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-01 18:26:30.210 WARN 5522 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-09-01 18:26:30.417 INFO 5522 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-09-01 18:26:30.420 INFO 5522 --- [ main] com.ab.SpringBootTry1Application : Started SpringBootTry1Application in 18.317 seconds (JVM running for 23.971)
2019-09-01 18:41:39.601 INFO 5522 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-09-01 18:41:39.602 INFO 5522 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-09-01 18:41:39.615 INFO 5522 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 13 ms
2019-09-01 18:47:48.219 WARN 5522 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Thread starvation or clock leap detected (housekeeper delta=6m18s959ms).
My code compiles fine.
Try to create new spring starter project from STS and do not touch spring boot main class and copy the same folder structure from here.Your code will definitely compiles.
I am learning SpringBoot. using Spring JavaPersistenceAPI(JPA) and apache derby as the database. I am having trouble mapping a URL to a method.
I have Topics:
#Entity
public class Topic {
#Id
private String id;
private String name;
private String description;
public Topic() {
}
public Topic(String id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
} ... getters & setters...
And I have a Topic controller. It works fine:
#RestController
public class TopicController {
#Autowired
private TopicService topicServ;
#RequestMapping("/topics")
public List<Topic> getAllTopics() {
return topicServ.getAllTopics();
}
#RequestMapping("/topics/{topicId}")
public Topic getTopic(#PathVariable String topicId) {
return topicServ.getTopic(topicId);
}... more methods (they work fine)
Every topic has courses:
#Entity
public class Course {
private String id;
private String name;
private String description;
#ManyToOne
private Topic topic;
public Course() {
}
public Course(String id, String name, String description, String topicId) {
this.id = id;
this.name = name;
this.description = description;
this.setTopic(new Topic(topicId, "CourseConstructorNAME", "CourseConstructorDESCRIPTION"));
} ... getters & setters ...
And I have the courses controller, where I am finding the problem:
#RestController
public class CourseController {
#Autowired
private CourseService courseServ;
#GetMapping(value = "/topics/{topicId}/courses")
public List<Course> getAllCourses(#PathVariable("topicId") String topicId){
System.out.println("Hi"); *<-- does not print anything*
return courseServ.getAllCourses(topicId);
}
The problem is that, issuing a GET request to http://localhost:8080/topics/java/courses , returns a 404 error message:
{
"timestamp": "2018-11-26T19:30:08.871+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/topics/java/courses"
}
I expect a list of courses corresponding to the topic id fetched from the URL. The failure confuses me because the topic controller works fine and it is almost the same.
So, because the sysout I put above doesn't print anything, I must be doing something really dumb; but just in case, here is the code for courseServ:
#Service
public class CourseService {
#Autowired
private CourseRepository courseRepo;
public List<Course> getAllCourses(String topicId){
System.out.println("Calling get all courses from course service");
List<Course> theList = new ArrayList<Course>();
courseRepo.findByTopic_Id(topicId).forEach(theList::add);
System.out.println(theList.toString());
return theList;
}
and here is courseRepo:
public interface CourseRepository extends CrudRepository<Course, String> {
public List<Course> findByTopic_Id(String topicId);
}
Here is the spring console log:
2018-11-26 13:29:25.142 INFO 16252 --- [ main] P.ProjectNameWithJpaApplication : Starting ProjectNameWithJpaApplication on JulioPHX with PID 16252 (C:\SpringToolSuite\workspace\ProjectNameWithJPA\target\classes started by JulioPHX in C:\SpringToolSuite\workspace\ProjectNameWithJPA)
2018-11-26 13:29:25.148 INFO 16252 --- [ main] P.ProjectNameWithJpaApplication : No active profile set, falling back to default profiles: default
2018-11-26 13:29:27.107 INFO 16252 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2018-11-26 13:29:27.238 INFO 16252 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 116ms. Found 1 repository interfaces.
2018-11-26 13:29:28.254 INFO 16252 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c18d73e6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-11-26 13:29:29.466 INFO 16252 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-11-26 13:29:29.501 INFO 16252 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-11-26 13:29:29.502 INFO 16252 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/9.0.12
2018-11-26 13:29:29.525 INFO 16252 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_191\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_191/bin/server;C:/Program Files/Java/jre1.8.0_191/bin;C:/Program Files/Java/jre1.8.0_191/lib/amd64;C:\Scripts\;C:\;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Python37\;C:\Python37\Scripts;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;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\Git\cmd;C:\Program Files\RedHat\java-1.8.0-openjdk-1.8.0.161-1\bin;C:\WINDOWS\System32\OpenSSH\;C:\MinGW\bin;C:\Program Files\MicrosoftVSCode\bin;C:\cygwin64\bin;C:\Program Files\apache-maven-3.5.4\bin;C:\Users\JulioPHX\AppData\Local\Microsoft\WindowsApps;;C:\Users\JulioPHX\Microsoft VS Code\bin;C:\SpringToolSuite\sts-bundle\sts-3.9.6.RELEASE;;.]
2018-11-26 13:29:29.773 INFO 16252 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-11-26 13:29:29.774 INFO 16252 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4461 ms
2018-11-26 13:29:29.852 INFO 16252 --- [ main] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-11-26 13:29:29.861 INFO 16252 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-11-26 13:29:29.862 INFO 16252 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-11-26 13:29:29.862 INFO 16252 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'formContentFilter' to: [/*]
2018-11-26 13:29:29.862 INFO 16252 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-11-26 13:29:30.698 INFO 16252 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-11-26 13:29:30.703 WARN 16252 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=org.apache.derby.jdbc.EmbeddedDriver was not found, trying direct instantiation.
2018-11-26 13:29:31.587 INFO 16252 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver does not support get/set network timeout for connections. (Feature not implemented: No details.)
2018-11-26 13:29:31.596 INFO 16252 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-11-26 13:29:31.764 INFO 16252 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-11-26 13:29:31.925 INFO 16252 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final}
2018-11-26 13:29:31.929 INFO 16252 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-11-26 13:29:32.247 INFO 16252 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2018-11-26 13:29:32.586 INFO 16252 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.DerbyTenSevenDialect
2018-11-26 13:29:34.603 WARN 16252 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "drop table topic" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "drop table topic" via JDBC Statement
Caused by: java.sql.SQLSyntaxErrorException: Schema 'SA' does not exist
Caused by: org.apache.derby.iapi.error.StandardException: Schema 'SA' does not exist
2018-11-26 13:29:34.718 INFO 16252 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#74b00247'
2018-11-26 13:29:34.725 INFO 16252 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-11-26 13:29:36.108 INFO 16252 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2018-11-26 13:29:36.251 WARN 16252 --- [ 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-11-26 13:29:36.757 INFO 16252 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-11-26 13:29:36.763 INFO 16252 --- [ main] P.ProjectNameWithJpaApplication : Started ProjectNameWithJpaApplication in 12.543 seconds (JVM running for 13.617)
2018-11-26 13:29:42.083 INFO 16252 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2018-11-26 13:29:42.084 INFO 16252 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2018-11-26 13:29:42.100 INFO 16252 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 16 ms
2018-11-26 13:29:42.298 INFO 16252 --- [nio-8080-exec-1] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
And the 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>PackageNameWithJPA</groupId>
<artifactId>ProjectNameWithJPA</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ProjectNameWithJPA</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.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-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</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>
Project structure:
Thank you in advance for any help.
I have same problem .It is because your Properties default is set to:
"spring.jpa.hibernate.ddl-auto=create-drop"
change it
in application.properties file.if this not over there add this
"spring.jpa.hibernate.ddl-auto=update"
line in your application.properties file.It work fine.
Even I have encountered the same error while using Apache Derby. This is because of the default properties of spring which is -spring.jpa.hibernate.ddl-auto=create-drop.
Solution: Create an application.properties file in src/main/resources folder and change the property to spring.jpa.hibernate.ddl-auto=update and run the app again, it should work.
The reason being the second controller in package "ProjectNameWithJPA.course" is giving 404 error because spring is not able to scan controller in "ProjectNameWithJPA.course".
By default, Spring-Boot scans the controller under the same package hierarchy like it can be "PackageNameWithJPA.course"
Read this for more understanding spring docs [https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html]
You can always define a custom component scan in a spring boot project. By default #SpringBootApplication annotation handles the component scanning for the application. However, let’s say one of the components is defined in another package then you can define in your configuration class like :
#ComponentScan({"com.springboot.basics.springbootPA1","com.springboot.springbootPA2"})
#SpringBootApplication
public class testApplication{
After read the demo in spring.ioI try to write a demo for spring boot jpa of my own.But when I ran the demo it has these problem.It said Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.model.Person.And here is the detail. I had made some changes, but I still have this problem.
17:55:40.430 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
17:55:40.432 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
17:55:40.432 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/E:/workspace-sts-3.8.4.RELEASE/demo/target/classes/]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.6.RELEASE)
2017-08-09 17:55:40.645 INFO 10472 --- [ restartedMain] com.example.demo.DemoApplication : Starting DemoApplication on MoriatyC with PID 10472 (E:\workspace-sts-3.8.4.RELEASE\demo\target\classes started by cmh in E:\workspace-sts-3.8.4.RELEASE\demo)
2017-08-09 17:55:40.645 INFO 10472 --- [ restartedMain] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2017-08-09 17:55:40.828 INFO 10472 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#617bc958: startup date [Wed Aug 09 17:55:40 CST 2017]; root of context hierarchy
2017-08-09 17:55:42.196 INFO 10472 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-08-09 17:55:42.208 INFO 10472 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-08-09 17:55:42.208 INFO 10472 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-08-09 17:55:42.299 INFO 10472 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-08-09 17:55:42.299 INFO 10472 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1474 ms
2017-08-09 17:55:42.433 INFO 10472 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-08-09 17:55:42.437 INFO 10472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-08-09 17:55:42.438 INFO 10472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-08-09 17:55:42.438 INFO 10472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-08-09 17:55:42.438 INFO 10472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-08-09 17:55:42.884 INFO 10472 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-08-09 17:55:42.898 INFO 10472 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-08-09 17:55:42.950 INFO 10472 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2017-08-09 17:55:42.951 INFO 10472 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-08-09 17:55:42.952 INFO 10472 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-08-09 17:55:43.045 INFO 10472 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-08-09 17:55:43.126 INFO 10472 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-08-09 17:55:43.259 INFO 10472 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2017-08-09 17:55:43.264 INFO 10472 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-08-09 17:55:43.288 INFO 10472 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-08-09 17:55:43.301 WARN 10472 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'searchController': Unsatisfied dependency expressed through field 'personRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.dao.PersonRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-08-09 17:55:43.302 INFO 10472 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-08-09 17:55:43.307 INFO 10472 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2017-08-09 17:55:43.317 INFO 10472 --- [ restartedMain] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-08-09 17:55:43.414 ERROR 10472 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field personRepository in com.example.controller.SearchController required a bean of type 'com.example.dao.PersonRepository' that could not be found.
Action:
Consider defining a bean of type 'com.example.dao.PersonRepository' in your configuration.
And here is the PersonRepository.java
package com.example.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.example.model.Person;
public interface PersonRepository extends JpaRepository<Person, Integer> {
List<Person> findByAddress(String address);
Person findByNameAndAddress(String name, String address);
#Query("select p from Person p where p.name = :name and p.address=:address")
Person withNameAndAddressQuery(#Param("name")String name, #Param("address")String address);
Person withNameAndAddressNamedQuery(String name, String address);
}
Person.java
package com.example.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Data
#NamedQuery(name="Person.withNameAndAddressNamedQuery", query = "select p from Person p where p.name=?1 and p.address=?2")
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private Integer age;
private String address;
}
SearchController.java
package com.example.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.dao.PersonRepository;
import com.example.model.Person;
#RestController
public class SearchController {
#Autowired
private PersonRepository personRepository;
#RequestMapping("/save")
public Person save(String name, String address, Integer age) {
Person p = personRepository.save(new Person(null, name, age, address));
return p;
}
#RequestMapping("/q1")
public List<Person> q1(String address) {
List<Person> people = personRepository.findByAddress(address);
return people;
}
#RequestMapping("/q2")
public Person q2(String name, String address) {
Person people = personRepository.findByNameAndAddress(name, address);
return people;
}
#RequestMapping("/q3")
public Person q3(String name, String address) {
Person people = personRepository.withNameAndAddressQuery(name, address);
return people;
}
public Person q4(String name, String address) {
Person p = personRepository.withNameAndAddressNamedQuery(name, address);
return p;
}
#RequestMapping("/sort")
public List<Person> sort() {
List<Person> people = personRepository.findAll(new Sort(Direction.ASC,"age"));
return people;
}
#RequestMapping("/page")
public Page<Person> page() {
Page<Person> pagePeople = personRepository.findAll(new PageRequest(1, 2));
return pagePeople;
}
}
Here is the 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.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>
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</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>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version><!--$NO-MVN-MAN-VER$ -->
<!-- <scope>provided</scope> -->
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
and this is the application.properties
spring.thymeleaf.mode=LEGACYHTML5
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jackson.serialization.indent-output=true
Here is my Application.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#ComponentScan(basePackages = "com.example")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
there is no problem with your code, the problem is the hierarchy of your project, the Application class should be in a parent level to your model, so it can scan your model, please check your files.
or you can add #SpringBootApplication like this :
#SpringBootApplication(scanBasePackages={"com.example.model"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}