I am new to coding. I am getting below error when trying to run java application in springboot with H2db.
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.777 s <<< FAILURE! - in com.example.demo.DemoApplicationTests
[ERROR] contextLoads(com.example.demo.DemoApplicationTests) Time elapsed: 0.002 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] DemoApplicationTests.contextLoads » IllegalState Failed to load ApplicationCon...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 13.028 s
[INFO] Finished at: 2019-05-26T22:46:54+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project demo: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\v\Desktop\demo\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
Here is my 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.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</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>
</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>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</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>
Application :
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.example.demo.StudentRepository;
#SpringBootApplication
#EntityScan("com.example.demo.Student")
#EnableJpaRepositories("com.example.demo.StudentRepository")
public class H2demoApplication implements CommandLineRunner {
// mvn spring-boot:run
private Logger LOG = LoggerFactory.getLogger("H2demoApplication");
StudentRepository studentRepository;
#Autowired
public H2demoApplication(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
public static void main(String[] args) {
SpringApplication.run(H2demoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
LOG.info("Student count in DB: {}", studentRepository.count());
}
}
Entity:
package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Student {
#Id
#GeneratedValue
private Long ID;
private String NAME;
private String SECTION;
public Student() {
}
public Student(Long ID, String NAME, String SECTION) {
this.ID = ID;
this.NAME = NAME;
this.SECTION = SECTION;
}
public Long getId() {
return ID;
}
public void setId(Long ID) {
this.ID = ID;
}
public String getName() {
return NAME;
}
public void setName(String NAME) {
this.NAME = NAME;
}
public String getSection() {
return SECTION;
}
public void setSection(String SECTION) {
this.SECTION = SECTION;
}
}
Repository:
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.Student;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
O/p should have "Student count in DB: 2"
my java version is :
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
Getting above error when running mvn clean install in command line.
I defined h2db configurations in application.properties file as below
H2 configurarion
spring.h2.console.enabled=true
spring.h2.console.path=/h2
Datasource
spring.datasource.url=jdbc:h2:~/test
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
in data.sql file kept data to be inserted :
insert into STUDENT
values(10001,'Ajay', 'AAA1');
insert into STUDENT
values(10002,'Ajit', 'AAA2');
You need to provide the hibernate dialect to configure hibernate befor connecting
use
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
The error looks like, it can't figure out the dialect to be used with H2.
The dialect specifies the type of database used in hibernate so that hibernate generate appropriate type of SQL statements.
The dialect to be used for h2 is this:
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Also being new to programming might confuse you to write optimal code. It looks like, you are mixing up things from older versions of spring boot and spring. Please use,
https://start.spring.io
to generate your initial spring boot project with the required dependencies. You can follow the below tutorial which explains nicely to get started with spring boot and h2.
https://www.springboottutorial.com/spring-boot-and-h2-in-memory-database
Related
I have below pom.xml in the SpringBoot application. While running the application, I am not facing any errors. But when I am hitting the URL through postman or browser, then my java code present inside controller is not getting executed.
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>MENU-RIGHT</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Controller:
package com.example.controller;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.model.MenuRightModel;
import com.example.service.MenuRightService;
#RestController
public class MenuRightController {
Logger logger = Logger.getAnonymousLogger();
#Autowired
private MenuRightService menuRightService;
#RequestMapping(value = "/getRightByUser/{id}", method=RequestMethod.GET)
public MenuRightModel findRightByUser(#PathVariable("id") int id) {
logger.info("Request Received for User Id : "+id);
return menuRightService.findRightByUser(id);
}
#RequestMapping(value = "/getRightAll", method=RequestMethod.GET)
public MenuRightModel findAllRight() {
return new MenuRightModel();
}
}
Project Execution Screenshot:
Postman Execution Screenshot:
Spring Boot Application Class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
#ComponentScan("src/main/java")
public class MenuRightApplication {
public static void main(String[] args) {
SpringApplication.run(MenuRightApplication.class, args);
}
}
Spring Boot Repository Class:
package com.dbs.repository;
import org.springframework.stereotype.Repository;
import com.example.model.MenuRightModel;
import org.springframework.data.jpa.repository.JpaRepository;
#Repository
public interface MenuRightRepository extends JpaRepository<MenuRightModel, Integer>{
MenuRightModel findByUserId(int id);
}
After Adding BasePackage as com.example facing below Exception:
2022-03-21 09:51:35.169 WARN 20560 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'menuRightController': Unsatisfied dependency expressed through field 'menuRightService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'menuRightServiceImpl': Unsatisfied dependency expressed through field 'menuRightRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.repository.MenuRightRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2022-03-21 09:51:35.172 INFO 20560 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-03-21 09:51:35.189 INFO 20560 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-03-21 09:51:35.312 ERROR 20560 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Field menuRightRepository in com.example.service.impl.MenuRightServiceImpl required a bean of type 'com.example.repository.MenuRightRepository' 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.example.repository.MenuRightRepository' in your configuration.
I am sure it is your main class configuration issue. By default, framework will scan beans in same package as of main class and sub-packages. e.g. below will not work
com/example/controller/FooController.java
com/example/main/MainClass.java
as applciation will scan for beans in com.example.main package and its subpackages only.
If that is case, you will need to update 'scanBasePackages' attribute of #SpringBootApplication annotation.
You need to add a package name in the component scan, in your case, it is #ComponentScan("com.example.controller"), Standard way to create other packages is
under the main root package
I get this error package org.junit doesn't exists in vscode when I import
import junit.framework.Test; or import static org.junit.Assert.assertEquals;
this is my test file
package com.wezigo.myapp.service;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MyServiceTest {
#Test
public void testCompute(){
MyService service =new MyService();
//MyService service = new MyService();
double a = 15;
double b = 15;
double expected = 20;
double result = service.compute(a,b);
assertEquals(expected, result,0.001 );
}
}
this is pom.xml file content
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wezigo</groupId>
<artifactId>myapp</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>myapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
</dependencies>
</project>
i try the solution in this address
**Why does vscode not recognize the import org.junit?
** but i use vscode 1.60.0 and this command is not availlable View -> Command Palette -> Java: Clean Java Language Server Workspace
when compile, i get thes error
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.083 s
[INFO] Finished at: 2021-09-24T12:10:31+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/home/rodolphe/javaTraining/work1). Please verify you invoked Maven from the correct directory. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MissingProjectException
Try
package com.wezigo.myapp.service;
public class MyServiceTest {
public void testCompute(){
MyService service =new MyService();
double a = 15;
double b = 15;
double expected = 20;
double result = service.compute(a,b);
assert Math.abs(expected - result) <= 0.001;
}
}
A popular fallacy is that you need junit for unit testing.
I am starting to use spring boot framework and stumble on every second step.
Currently I have a situation which i absolutely do not understand.
I am using spring boot 2.3.5.RELEASE building with maven
<properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.6.Final</version>
</dependency>
<!-- OpenAPi (swagger)-->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.2.32</version>
</dependency>
</dependencies>
I created a rather simple class RESTCommunication. No #Component, #Controller or similar.
public class RESTCommunication {
private final Logger m_logger = LoggerFactory.getLogger(this.getClass());
private String m_contentType;
private String m_path;
private String m_body;
private HashMap<String,String> m_urlParams;
private HashMap<String,String> m_queryParams;
public RESTCommunication() {
m_logger.debug("RESTCommunication constructor");
m_scheme = RESTCommunication.SCHEME_DEFAULT;
m_authority = RESTCommunication.AUTHORITY_DEFAULT;
m_port = RESTCommunication.PORT_DEFAULT;
m_path = RESTCommunication.PATH_DEFAULT;
m_urlParams = new HashMap<>();
// m_queryParams = new HashMap<>(); // I know that this is the reason for the exception
}
#Override
public String toString() {
StringBuilder sbToString = new StringBuilder();
sbToString.append(buildURI());
sbToString.append("|numURLParams:").append(m_urlParams.size());
sbToString.append("|numQueryParams:").append(m_queryParams.size()); // This has to fail because m_queryParams is not initialized
return sbToString.toString();
}
.....
For this class i created a very simple test class RESTCommunicationTest
#SpringBootTest
public class RESTCommunicationTest {
private final Logger m_logger = LoggerFactory.getLogger(this.getClass());
#Test
public void defaultInitTest() {
RESTCommunication restComm = new RESTCommunication();
String restCommURL = restComm.toString(); // Expect the nullpointer INSIDE the toString method
String expectedURL = sbExpected.toString();
assertEquals(expectedURL, restCommURL, "Expected URL does not match generated");
}
I run the test with the command: $./mvnw -e -X package -Dtest=RESTCommunicationTest#defaultInitTest
And as expectable i see the Nullpointer in the stdout logging.
BUT in the logging I find this:
webServerFactoryCustomizerBeanPostProcessor
websocketServletWebServerCustomizer
welcomePageHandlerMapping
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.532 s <<< FAILURE! - in org.highpots.hippo.core.communication.RESTCommunicationTest
[ERROR] defaultInitTest Time elapsed: 0.399 s <<< ERROR!
java.lang.NullPointerException
at org.ilovespringboot.not.RESTCommunicationTest.defaultInitTest(RESTCommunicationTest.java:36)
2020-12-08 22:18:10.810 INFO 10381 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] RESTCommunicationTest.defaultInitTest:36 » NullPointer
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
A nullpointer in RESTCommunicationTest.java:36. Absolutely no hint that the real NullPointer happens in RESTCommunication class.
Can someone explain my that behaviour? Am I doing something wrong?
I know I am some kind of programming dinosaurs. (java projects are about 10+ years in the past). But I would expect to get a hint where the exception is thrown. I would expect a stacktrace with detailed caused by sections.
If can not imagine this is not normal behavior. Because that would mean I have to find all errors by mind-stepping through the complete source... This is not possible
Tanks for your help in advance
Harri E
Maven uses surefire plugin to run tests.To see Exception stacktrace you must set trimStackTrace to false in surefire plugin configuration.
Historically surefire plugin use to print complete stacktrace. Though the information in the stack trace was useful for debugging, stack traces took up rather a lot of space in the console output. Particularly if there were a number of failing tests it became easy to get lost in the noise.
Since version 2.13 surefire just prints summary by default.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${your.maven.surefire.version.here}</version>
<configuration>
<trimStackTrace>false</trimStackTrace>
</configuration>
</plugin>
</plugins>
</build>
I'm trying to build my project and I keep getting an error, saying the package doesn't exist why the IDE says it's fine (no compile error). Obviously, something is not consistent between my pom.xml and the way the IDE compiles.
Here how my project structure looks like:
Here is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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.oo</groupId>
<artifactId>employeeservice</artifactId> <!-- Docker complains if the name contains upper case -->
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>EmployeeService</name>
<description>This service takes care of all the employee related operations</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
If I remove Employee (entity) and EmployeeRepository and just have the controller with a dummy "Hello World", it works fine! I tried to put them under the same package, same issue!
Employee class
package com.oo.employeeservice.dao.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String firtName;
private String lastName;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirtName() {
return firtName;
}
public void setFirtName(String firtName) {
this.firtName = firtName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Using default Spring boot configuration:
package com.oo.employeeservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
Controller
package com.oo.employeeservice.controller;
import com.oo.employeeservice.dao.EmployeeRepository;
import com.oo.employeeservice.dao.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping("/api")
public class EmployeeController {
#Autowired
private EmployeeRepository repo;
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Iterable<Employee>> all() {
return new ResponseEntity<Iterable<Employee>>(repo.findAll(), HttpStatus.OK);
}
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> create(#RequestBody Employee employee) {
repo.save(employee);
return new ResponseEntity<String>(HttpStatus.CREATED);
}
}
Maven log:
~/IdeaProjects/EmployeeService$ mvn clean install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building EmployeeService 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.0.0:clean (default-clean) # employeeservice ---
[INFO] Deleting /home/mahdi/IdeaProjects/EmployeeService/target
[INFO]
[INFO] --- maven-resources-plugin:3.0.1:resources (default-resources) # employeeservice ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) # employeeservice ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to /home/mahdi/IdeaProjects/EmployeeService/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/dao/EmployeeRepository.java:[3,41] package com.oo.employeeservice.dao.entity does not exist
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/dao/EmployeeRepository.java:[9,60] cannot find symbol
symbol: class Employee
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/controller/EmployeeController.java:[4,41] package com.oo.employeeservice.dao.entity does not exist
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/controller/EmployeeController.java:[18,36] cannot find symbol
symbol: class Employee
location: class com.oo.employeeservice.controller.EmployeeController
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/controller/EmployeeController.java:[23,50] cannot find symbol
symbol: class Employee
location: class com.oo.employeeservice.controller.EmployeeController
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/controller/EmployeeController.java:[19,44] cannot find symbol
symbol: class Employee
location: class com.oo.employeeservice.controller.EmployeeController
[INFO] 6 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.872 s
[INFO] Finished at: 2018-07-15T15:59:38+08:00
[INFO] Final Memory: 31M/308M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project employeeservice: Compilation failure: Compilation failure:
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/dao/EmployeeRepository.java:[3,41] package com.oo.employeeservice.dao.entity does not exist
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/dao/EmployeeRepository.java:[9,60] cannot find symbol
[ERROR] symbol: class Employee
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/controller/EmployeeController.java:[4,41] package com.oo.employeeservice.dao.entity does not exist
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/controller/EmployeeController.java:[18,36] cannot find symbol
[ERROR] symbol: class Employee
[ERROR] location: class com.oo.employeeservice.controller.EmployeeController
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/controller/EmployeeController.java:[23,50] cannot find symbol
[ERROR] symbol: class Employee
[ERROR] location: class com.oo.employeeservice.controller.EmployeeController
[ERROR] /home/mahdi/IdeaProjects/EmployeeService/src/main/java/com/oo/employeeservice/controller/EmployeeController.java:[19,44] cannot find symbol
[ERROR] symbol: class Employee
[ERROR] location: class com.oo.employeeservice.controller.EmployeeController
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
I found the silliest problem with Intellij. If you look for Employee class in the package explorer in the image attached, you can see the file is marked as a class. When I opened the file location in the terminal, I realized it doesn't have ".java" extension. Obviously, maven won't recognize the file as a java file!
I have faced the same issue once. The problem was I have created the folder structure with name test.demo.exmple.java and it got created in the same way in explorer ( this can be seen if you open same files on explorer) means folder name was test.demo where the system is looking for test/demo/example.java.
So in your case I think path would be com.oo.employeeservice instead of com/oo/employeeservice
I created a Spring Boot Maven project, however my RequestMapping, as well as localhost:8080 return a 404 error page. I think the issue is with how my packages are setup, but I've tried solutions in multiple questions, and I still cant get around the error page. Could you guys point me in the right direction as to how to resolve this issue? Perhaps I need to add the Component annotation above my Main class? But I've tried this solution, and the error still persists.
Here is my package structure:
/src/main/java
ControllerLayer
UsersController.java
DataAccessLayer
UsersDAL.java
ServiceLayer
UsersService.java
Main
Main.java
Main.java:
#SpringBootApplication(scanBasePackages = {
"/src/main/java/ControllerLayer", "/src/main/java/DataAccessLayer",
"/src/main/java/ServiceLayer" })
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
UsersController.java:
import Entities.Users;
import ServiceLayer.UsersService;
#RestController
#RequestMapping("/users")
public class UsersController {
#Autowired
private UsersService usersService;
#RequestMapping(value =
"/create/{userId}/{userPassword}/{userAge}/{userEmail}"
+ "/{userFirstName}/{userlastName}", method =
RequestMethod.POST)
public void createUser(#PathVariable("userId")String userId,
#PathVariable("userPassword")String userPassword,
#PathVariable("userAge")int userAge,
#PathVariable("userEmail")String userEmail,
#PathVariable("userFirstName")String userFirstName,
#PathVariable("userLastName")String userLastName) {
usersService.createUser(new Users(userId, userPassword,
userAge, userEmail, userFirstName, userLastName));
}
}
UserService.java
import DataAccessLayer.UsersDAL;
import Entities.Users;
#Service
public class UsersService {
#Autowired
private UsersDAL usersDAL;
public void createUser(Users user) {
usersDAL.createUser(user);
}
}
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>xProjectAlpha</groupId>
<artifactId>org.htech.xProjectAlpha</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version><!--$NO-MVN-MAN-VER$-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
When a request is sent, then a response shall be returned. In your case, you didn't send any content with the response and that's why you get 404 error (page not found).
In main.java, try:
#SpringBootApplication(scanBasePackages = {
"ControllerLayer", "DataAccessLayer",
"ServiceLayer" })
Your package names shouldn't include the root path in the project.
It is advisable to have spring boot Application class in root package and have all other classes in package structure below that package .You don't have to worry about component scan as an example
package com.igt.customer;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
#SpringBootApplication
public class CustomerApplication {
public static void main(String[] args) {
SpringApplication.run(CustomerApplication.class, args);
}
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
Controller class
package com.igt.customer.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class EmployeeController {
#RequestMapping("/employee")
public String employee() {
return "Greetings from Sam!";
}
}
running the application (go to the directory of your application on cmd )
E:\MongoDb\New folder\customer>mvn install -U -e
you should see this in the end if its fine
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.686 s
[INFO] Finished at: 2017-08-16T16:39:57+05:30
[INFO] Final Memory: 21M/219M
[INFO] ------------------------------------------------------------------------
run the jar file
E:\MongoDb\New folder\customer\target>java -jar customer-0.0.1-SNAPSHOT.jar
accessing the application
http://localhost:8080/employee
Notice application name is not required in URL
P.S i have written extra detail here as i have experienced if you are new to spring boot building and running the application is a challenge , in my application i had created a rest controller in the same package as the Application class with RequestMapping "/" as i was getting 404 error , Please see the link below as a reference
spring boot application
This issue will be simply solved if you remove the main package of the main.java class.
The new structure will be:
/src/main/java
Main.java
ControllerLayer
UsersController.java
DataAccessLayer
UsersDAL.java
ServiceLayer
UsersService.java
In my Spring boot application, there is no need to scan the base packages manually because all the configurations are embedded in a single annotation #SpringBootApplication. Please refer to this link.
I don't understand how the base packages are initially configured. Can someone please explain this?
For example, if your base package looks like:
com.example.myapp.SpringApplication
... it means your application takes base packages as com.example.myapp. So if you can create all Controllers, Service, Repository under com.example.myapp in the sense it will load your Controllers, Service, Repository easily or else it can't able to load. This is because springbootapplication intially sets the base packages and loads whatever java classes are inside the base package. So because of this you get a 404 error in the browser as well as in postman. So try to match with base package.