Just testing some Spring Boot 3.0.0 with GraalVM Native and got some queries regarding it as I could not find properly documentation regarding it.
So, I've started a new project with GraalVM Native Support and Spring Web depedencies on Spring Initializr (https://start.spring.io/).
Then, for testing native image purposes I have my DemoApplication class like as follows:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import jakarta.servlet.http.HttpServletRequest;
#SpringBootApplication(proxyBeanMethods = false)
public class DemoApplication {
#Autowired
private HttpServletRequest request;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
As a result to build a native image, have used command as follows:
mvn -Pnative spring-boot:build-image
The image was successfully compiled and created:
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
paketobuildpacks/run tiny-cnb c71fb787280a 3 days ago 17.3MB
paketobuildpacks/builder tiny cf7ea4946a20 42 years ago 588MB
demo 0.0.1-SNAPSHOT 7794949d07ce 42 years ago 96.9MB
When I run this "demo" image using:
docker run demo:0.0.1-SNAPSHOT
It shows the following exception:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.0)
2022-12-16T21:23:41.386Z INFO 1 --- [ main] com.example.demo.DemoApplication : Starting AOT-processed DemoApplication using Java 17.0.5 with PID 1 (/workspace/com.example.demo.DemoApplication started by cnb in /workspace)
2022-12-16T21:23:41.386Z INFO 1 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default"
2022-12-16T21:23:41.395Z INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-12-16T21:23:41.396Z INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-12-16T21:23:41.396Z INFO 1 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.1]
2022-12-16T21:23:41.399Z INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-12-16T21:23:41.400Z INFO 1 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 14 ms
2022-12-16T21:23:41.403Z WARN 1 --- [ main] w.s.c.ServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'demoApplication': Instantiation of supplied bean failed
2022-12-16T21:23:41.403Z INFO 1 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-12-16T21:23:41.404Z ERROR 1 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'demoApplication': Instantiation of supplied bean failed
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.obtainInstanceFromSupplier(AbstractAutowireCapableBeanFactory.java:1236) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.obtainFromSupplier(AbstractAutowireCapableBeanFactory.java:1210) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1157) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:561) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:961) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:915) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[com.example.demo.DemoApplication:3.0.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[com.example.demo.DemoApplication:3.0.0]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432) ~[com.example.demo.DemoApplication:3.0.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[com.example.demo.DemoApplication:3.0.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[com.example.demo.DemoApplication:3.0.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291) ~[com.example.demo.DemoApplication:3.0.0]
at com.example.demo.DemoApplication.main(DemoApplication.java:16) ~[com.example.demo.DemoApplication:na]
Caused by: com.oracle.svm.core.jdk.UnsupportedFeatureError: Proxy class defined by interfaces [interface jakarta.servlet.http.HttpServletRequest] not found. Generating proxy classes at runtime is not supported. Proxy classes need to be defined at image build time by specifying the list of interfaces that they implement. To define proxy classes use -H:DynamicProxyConfigurationFiles=<comma-separated-config-files> and -H:DynamicProxyConfigurationResources=<comma-separated-config-resources> options.
at com.oracle.svm.core.util.VMError.unsupportedFeature(VMError.java:89) ~[na:na]
at com.oracle.svm.core.reflect.proxy.DynamicProxySupport.getProxyClass(DynamicProxySupport.java:171) ~[na:na]
at java.base#17.0.5/java.lang.reflect.Proxy.getProxyConstructor(Proxy.java:47) ~[com.example.demo.DemoApplication:na]
at java.base#17.0.5/java.lang.reflect.Proxy.newProxyInstance(Proxy.java:1037) ~[com.example.demo.DemoApplication:na]
at org.springframework.beans.factory.support.AutowireUtils.resolveAutowiringValue(AutowireUtils.java:134) ~[na:na]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1576) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1368) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1325) ~[com.example.demo.DemoApplication:6.0.2]
at org.springframework.beans.factory.aot.AutowiredFieldValueResolver.resolveValue(AutowiredFieldValueResolver.java:189) ~[na:na]
at org.springframework.beans.factory.aot.AutowiredFieldValueResolver.resolveAndSet(AutowiredFieldValueResolver.java:167) ~[na:na]
at com.example.demo.DemoApplication__Autowiring.apply(DemoApplication__Autowiring.java:14) ~[na:na]
at org.springframework.beans.factory.support.InstanceSupplier$1.get(InstanceSupplier.java:82) ~[na:na]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.obtainInstanceFromSupplier(AbstractAutowireCapableBeanFactory.java:1225) ~[com.example.demo.DemoApplication:6.0.2]
... 18 common frames omitted
I assume that must be something related to inform a implementation for interface jakarta.servlet.http.HttpServletRequest, however I don't how to inform/configure it.
Do you guys have any suggestion(s)?
Thanks in advance.
After several readings on Spring Boot 3.0.0 (https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/) user guide, have figured out that some classes Spring AOT needs a runtime hint as a result to compile it into a native program.
If the class is not found you need to create a custom hint (https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#native-image.advanced.custom-hints).
So to have it worked I have created a HTTPServletRequest runtime hint (bear in mind that must implements interface org.springframework.aot.hint.RuntimeHintsRegistrar) class as follows:
public class HttpServletRequestRuntimeHint implements RuntimeHintsRegistrar{
#Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
try {
ProxyHints proxies = hints.proxies();
proxies.registerJdkProxy(HttpServletRequest.class);
} catch (Exception e) {
throw new RuntimeException("Could not register RuntimeHint: " + e.getMessage());
}
}
}
And then it needs to be informed on a #Configuration class or, for example, your #SpringBootApplication annotated application class to activate those hints:
#SpringBootApplication
#ImportRuntimeHints(value = {HttpServletRequestRuntimeHint.class})
public class DemoApplication {
#Autowired
private HttpServletRequest request;
public static void main(String[] args) {
SpringApplication.run(ApplicationConfig.class, args);
}
}
And done!
Hope that helps!
Thank you.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
Working in intellij community edition.
How can i resolve this error. I have tried everything i could find on stackoverflow
Console
C:\Users\dell\.jdks\openjdk-17.0.2\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2021.3.1\lib\idea_rt.jar=60395:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2021.3.1\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\dell\OneDrive\Desktop\dailyWagers\target\classes;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-data-jpa\2.6.3\spring-boot-starter-data-jpa-2.6.3.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-aop\2.6.3\spring-boot-starter-aop-2.6.3.jar;C:\Users\dell\.m2\repository\org\aspectj\aspectjweaver\1.9.7\aspectjweaver-1.9.7.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-jdbc\2.6.3\spring-boot-starter-jdbc-2.6.3.jar;C:\Users\dell\.m2\repository\com\zaxxer\HikariCP\4.0.3\HikariCP-4.0.3.jar;C:\Users\dell\.m2\repository\org\springframework\spring-jdbc\5.3.15\spring-jdbc-5.3.15.jar;C:\Users\dell\.m2\repository\jakarta\transaction\jakarta.transaction-api\1.3.3\jakarta.transaction-api-1.3.3.jar;C:\Users\dell\.m2\repository\jakarta\persistence\jakarta.persistence-api\2.2.3\jakarta.persistence-api-2.2.3.jar;C:\Users\dell\.m2\repository\org\hibernate\validator\hibernate-validator\6.2.0.Final\hibernate-validator-6.2.0.Final.jar;C:\Users\dell\.m2\repository\jakarta\validation\jakarta.validation-api\2.0.2\jakarta.validation-api-2.0.2.jar;C:\Users\dell\.m2\repository\org\jboss\logging\jboss-logging\3.4.3.Final\jboss-logging-3.4.3.Final.jar;C:\Users\dell\.m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar;C:\Users\dell\.m2\repository\org\springframework\data\spring-data-jpa\2.6.1\spring-data-jpa-2.6.1.jar;C:\Users\dell\.m2\repository\org\springframework\data\spring-data-commons\2.6.1\spring-data-commons-2.6.1.jar;C:\Users\dell\.m2\repository\org\springframework\spring-orm\5.3.15\spring-orm-5.3.15.jar;C:\Users\dell\.m2\repository\org\springframework\spring-context\5.3.15\spring-context-5.3.15.jar;C:\Users\dell\.m2\repository\org\springframework\spring-tx\5.3.15\spring-tx-5.3.15.jar;C:\Users\dell\.m2\repository\org\springframework\spring-beans\5.3.15\spring-beans-5.3.15.jar;C:\Users\dell\.m2\repository\org\slf4j\slf4j-api\1.7.33\slf4j-api-1.7.33.jar;C:\Users\dell\.m2\repository\org\springframework\spring-aspects\5.3.15\spring-aspects-5.3.15.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-security\2.6.3\spring-boot-starter-security-2.6.3.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter\2.6.3\spring-boot-starter-2.6.3.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot\2.6.3\spring-boot-2.6.3.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.6.3\spring-boot-autoconfigure-2.6.3.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-logging\2.6.3\spring-boot-starter-logging-2.6.3.jar;C:\Users\dell\.m2\repository\ch\qos\logback\logback-classic\1.2.10\logback-classic-1.2.10.jar;C:\Users\dell\.m2\repository\ch\qos\logback\logback-core\1.2.10\logback-core-1.2.10.jar;C:\Users\dell\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.17.1\log4j-to-slf4j-2.17.1.jar;C:\Users\dell\.m2\repository\org\apache\logging\log4j\log4j-api\2.17.1\log4j-api-2.17.1.jar;C:\Users\dell\.m2\repository\org\slf4j\jul-to-slf4j\1.7.33\jul-to-slf4j-1.7.33.jar;C:\Users\dell\.m2\repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;C:\Users\dell\.m2\repository\org\yaml\snakeyaml\1.29\snakeyaml-1.29.jar;C:\Users\dell\.m2\repository\org\springframework\spring-aop\5.3.15\spring-aop-5.3.15.jar;C:\Users\dell\.m2\repository\org\springframework\security\spring-security-config\5.6.1\spring-security-config-5.6.1.jar;C:\Users\dell\.m2\repository\org\springframework\security\spring-security-web\5.6.1\spring-security-web-5.6.1.jar;C:\Users\dell\.m2\repository\org\springframework\spring-expression\5.3.15\spring-expression-5.3.15.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-web\2.6.3\spring-boot-starter-web-2.6.3.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-json\2.6.3\spring-boot-starter-json-2.6.3.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.13.1\jackson-databind-2.13.1.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.13.1\jackson-annotations-2.13.1.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.13.1\jackson-core-2.13.1.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.13.1\jackson-datatype-jdk8-2.13.1.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.13.1\jackson-datatype-jsr310-2.13.1.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.13.1\jackson-module-parameter-names-2.13.1.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-tomcat\2.6.3\spring-boot-starter-tomcat-2.6.3.jar;C:\Users\dell\.m2\repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.56\tomcat-embed-core-9.0.56.jar;C:\Users\dell\.m2\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.56\tomcat-embed-el-9.0.56.jar;C:\Users\dell\.m2\repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.56\tomcat-embed-websocket-9.0.56.jar;C:\Users\dell\.m2\repository\org\springframework\spring-web\5.3.15\spring-web-5.3.15.jar;C:\Users\dell\.m2\repository\org\springframework\spring-webmvc\5.3.15\spring-webmvc-5.3.15.jar;C:\Users\dell\.m2\repository\mysql\mysql-connector-java\8.0.28\mysql-connector-java-8.0.28.jar;C:\Users\dell\.m2\repository\org\projectlombok\lombok\1.18.22\lombok-1.18.22.jar;C:\Users\dell\.m2\repository\org\springframework\spring-core\5.3.15\spring-core-5.3.15.jar;C:\Users\dell\.m2\repository\org\springframework\spring-jcl\5.3.15\spring-jcl-5.3.15.jar;C:\Users\dell\.m2\repository\org\springframework\security\spring-security-core\5.6.1\spring-security-core-5.6.1.jar;C:\Users\dell\.m2\repository\org\springframework\security\spring-security-crypto\5.6.1\spring-security-crypto-5.6.1.jar com.burrows.dailyWagers.DailyWagersApplication
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.3)
2022-02-04 23:09:16.239 INFO 1328 --- [ main] c.b.dailyWagers.DailyWagersApplication : Starting DailyWagersApplication using Java 17.0.2 on DESKTOP-UNKQR00 with PID 1328 (C:\Users\dell\OneDrive\Desktop\dailyWagers\target\classes started by dell in C:\Users\dell\OneDrive\Desktop\dailyWagers)
2022-02-04 23:09:16.246 INFO 1328 --- [ main] c.b.dailyWagers.DailyWagersApplication : No active profile set, falling back to default profiles: default
2022-02-04 23:09:19.421 INFO 1328 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-02-04 23:09:19.586 INFO 1328 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 114 ms. Found 1 JPA repository interfaces.
2022-02-04 23:09:21.367 INFO 1328 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2022-02-04 23:09:21.408 INFO 1328 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-02-04 23:09:21.409 INFO 1328 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-02-04 23:09:21.621 INFO 1328 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-02-04 23:09:21.622 INFO 1328 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 5248 ms
2022-02-04 23:09:21.765 WARN 1328 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'controller': Unsatisfied dependency expressed through field 'workerService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.burrows.dailyWagers.service.WorkerService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2022-02-04 23:09:21.771 INFO 1328 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-02-04 23:09:21.818 INFO 1328 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-02-04 23:09:21.881 ERROR 1328 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field workerService in com.burrows.dailyWagers.controller.Controller required a bean of type 'com.burrows.dailyWagers.service.WorkerService' 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.burrows.dailyWagers.service.WorkerService' in your configuration.
Process finished with exit code 1
Controller.java
package com.burrows.dailyWagers.controller;
import com.burrows.dailyWagers.model.Worker;
import com.burrows.dailyWagers.service.WorkerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/workers")
public class Controller {
#Autowired
private WorkerService workerService;
#GetMapping("/{workerType}")
public List<Worker> getWorkers(#PathVariable String workerType){
return this.workerService.getWorkers(workerType);
}
#GetMapping("/{id}")
public Worker getWorker(#PathVariable Long id){
return (Worker) this.workerService.getWorkers(String.valueOf(id));
}
#PostMapping("/{worker}")
public void postWorker(#PathVariable Worker worker){
this.workerService.postWorker(worker);
}
#PutMapping("/{worker}")
public void updateWorker(#PathVariable Worker worker){
this.workerService.updateWorker(worker);
}
#DeleteMapping("/{id}")
public ResponseEntity<HttpStatus> deleteWorker(#PathVariable Long id){
try {
this.workerService.deleteWorker(id);
return new ResponseEntity<>(HttpStatus.OK);
}
catch(Exception e){
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
WorkerService.java
package com.burrows.dailyWagers.service;
import com.burrows.dailyWagers.model.Worker;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public interface WorkerService {
public List<Worker> getWorkers(String workerType);
public Worker getWorker(Long id);
public void postWorker(Worker worker);
public void deleteWorker(Long id);
public void updateWorker(Worker worker);
}
WorkerServiceImpl
package com.burrows.dailyWagers.service;
import com.burrows.dailyWagers.model.Worker;
import com.burrows.dailyWagers.repository.WorkerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class WorkerServiceImpl implements WorkerService{
#Autowired
private WorkerRepository workerRepository;
public List<Worker> getWorkers(String workerType) {
return workerRepository.findAll();
}
public Worker getWorker(Long id) {
return workerRepository.getById(id);
}
public void postWorker(Worker worker) {
workerRepository.save(worker);
}
public void deleteWorker(Long id) {
Worker workerToBeDeleted = workerRepository.getById(id);
workerRepository.delete(workerToBeDeleted);
}
public void updateWorker(Worker worker) {
workerRepository.save(worker);
}
}
WorkerRepository.java
package com.burrows.dailyWagers.repository;
import com.burrows.dailyWagers.model.Worker;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface WorkerRepository extends JpaRepository<Worker,Long> {
}
Worker.java
package com.burrows.dailyWagers.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.List;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Builder
public class Worker {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String workerType;
private String servicesOffered;
private LocalDate availability;
private Integer rating;
}
application.properties
server.port=8081
#mysql configuration
spring.datasource.url=jdbc:mysql://localhost:3306/maid-app-db
spring.datasource.username=root
spring.datasource.password=5856
spring.datasource.driverClassName=com.mysql.jdbc.Driver
#hibernate configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
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.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.burrows</groupId>
<artifactId>dailyWagers</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>dailyWagers</name>
<description>daily wagers web application</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
I faced same issue when i was beginner in Spring Framework. If put #Service annotaion on interface then service interface become useless so, Remove #Service annotation from WorkerService and put this annotation in WorkerServiceImpl.
I am started building a spring boot application but i am getting this type of error "Whitelabel Error Page - This application has no configured error view, so you are seeing this as a fallback."
I created the project from https://start.spring.io/.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.3.RELEASE)
2020-09-09 16:12:00.389 INFO 19440 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication on ***** with PID 19440 (C:\Users\m.petraglia\Desktop\demo\target\classes started by m.petraglia in C:\Users\m.petraglia\Desktop\demo)
2020-09-09 16:12:00.391 INFO 19440 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2020-09-09 16:12:01.024 DEBUG 19440 --- [ main] o.s.w.r.handler.SimpleUrlHandlerMapping : Patterns [/webjars/**, /**] in 'resourceHandlerMapping'
2020-09-09 16:12:01.118 DEBUG 19440 --- [ main] o.s.w.r.r.m.a.ControllerMethodResolver : ControllerAdvice beans: none
2020-09-09 16:12:01.138 DEBUG 19440 --- [ main] o.s.w.s.adapter.HttpWebHandlerAdapter : enableLoggingRequestDetails='false': form data and headers will be masked to prevent unsafe logging of potentially sensitive data
2020-09-09 16:12:01.961 INFO 19440 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2020-09-09 16:12:01.967 INFO 19440 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 1.837 seconds (JVM running for 2.132)
2020-09-09 16:12:07.977 DEBUG 19440 --- [ctor-http-nio-2] o.s.w.s.adapter.HttpWebHandlerAdapter : [22183960-1] HTTP GET "/hello"
2020-09-09 16:12:07.998 DEBUG 19440 --- [ctor-http-nio-2] o.s.w.r.handler.SimpleUrlHandlerMapping : [22183960-1] Mapped to ResourceWebHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"]
2020-09-09 16:12:08.000 DEBUG 19440 --- [ctor-http-nio-2] o.s.w.r.resource.ResourceWebHandler : [22183960-1] Resource not found
2020-09-09 16:12:08.025 DEBUG 19440 --- [ctor-http-nio-2] org.springframework.web.HttpLogging : [22183960-1] Resolved [ResponseStatusException: 404 NOT_FOUND] for HTTP GET /hello
2020-09-09 16:12:08.031 DEBUG 19440 --- [ctor-http-nio-2] org.springframework.web.HttpLogging : [22183960-1] Writing "<html><body><h1>Whitelabel Error Page</h1><p>This application has no configured error view, so you (truncated)...
2020-09-09 16:12:08.042 DEBUG 19440 --- [ctor-http-nio-2] o.s.w.s.adapter.HttpWebHandlerAdapter : [22183960-1] Completed 404 NOT_FOUND
DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#GetMapping("/hello")
public String hello(#RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
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.3.3.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-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-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:
I don't understand what is the problem.
Try adding #RestController annotation to the class
maybe you should use html file to run it in browser in my opinion,and also if you use thymeleaf include the dependencies as well
I was following an example from the spring boot documentation and the java controller always returns a 404 for some reason
This is what I tried
package com.example.accessingdatamysql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller // This means that this class is a Controller
#RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {
#Autowired // This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it to handle the data
private UserRepository userRepository;
#PostMapping(path="/add") // Map ONLY POST Requests
public #ResponseBody String addNewUser (#RequestParam String name
, #RequestParam String email) {
// #ResponseBody means the returned String is the response, not a view name
// #RequestParam means it is a parameter from the GET or POST request
User n = new User();
n.setName(name);
n.setEmail(email);
userRepository.save(n);
return "Saved";
}
#GetMapping(path="/all")
public #ResponseBody Iterable<User> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
}
}
which is the example given by spring boot here https://spring.io/guides/gs/accessing-data-mysql/
Then I also tried
#RestController
#RequestMapping("/demo")
public class GreetingClass {
#GetMapping("/greeting")
public String getGreeting() {
return "hello";
}
}
.pom file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 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.3.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.braintobytes</groupId>
<artifactId>Finance_microservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Finance_microservice</name>
<description>Finance service</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</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-webflux</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-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>
I know this is weird, I set up everything as instructed on the page but apparently nothing works, and I also checked other questions similar to this none of them answer my question.
It does seem that the tomcat server is hit, because it says when I make a call
o.s.web.servlet.DispatcherServlet : Completed initialization in 9 ms
but then I get with this call curl 'http://localhost:8080/demo/greeting' and with 'http://localhost:8080/demo/all'
curl : The remote server returned an error: (404) Not Found.
Logs (the file path is removed on the first line):
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.2.RELEASE)
2020-08-31 08:19:16.508 INFO 20708 --- [ main] c.b.f.FinanceMicroserviceApplication : Starting FinanceMicroserviceApplication on DESKTOP-A65224I with PID 20708 ()
2020-08-31 08:19:16.510 INFO 20708 --- [ main] c.b.f.FinanceMicroserviceApplication : No active profile set, falling back to default profiles: default
2020-08-31 08:19:17.096 INFO 20708 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-08-31 08:19:17.101 INFO 20708 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-31 08:19:17.101 INFO 20708 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-31 08:19:17.150 INFO 20708 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-31 08:19:17.150 INFO 20708 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 618 ms
2020-08-31 08:19:17.465 INFO 20708 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-31 08:19:17.675 INFO 20708 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-31 08:19:17.681 INFO 20708 --- [ main] c.b.f.FinanceMicroserviceApplication : Started FinanceMicroserviceApplication in 1.328 seconds (JVM running for 1.835)
2020-08-31 08:20:21.893 INFO 20708 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-31 08:20:21.893 INFO 20708 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-08-31 08:20:21.905 INFO 20708 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 12 ms
Response:
{
"timestamp": "2020-08-31T13:20:21.930+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/demo/greeting"
}
This works if I do this:
https://github.com/BraintoByte/Test_App_Stack/tree/master/demo
Different example:
I have attached a different example with hirarchy exactly the same but business logic omitted:
Code in controller:
package com.braintobytes.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.braintobytes.data.Currency;
import com.braintobytes.data.repository.CurrencyRepository;
#RestController
#RequestMapping("/demo")
public class CurrencyController {
#Autowired
private CurrencyRepository currencyRepository;
#GetMapping("/currency")
public String getCurrency() {
return "currency";
}
}
Project hierarchy:
Same exact pom and in application.properties:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mydatabase
spring.datasource.username=myusername
spring.datasource.password=mypassword
Your controller is in package - com.example.accessingdatamysql
Spring boot startup log shows your main application class c.b.f.FinanceMicroserviceApplication is in another non related package hierarchy.
Spring boot recommends to locate main application class in a root package above other classes so that the component scan works out of box.
If you keep package com.example as root package and move your main application class FinanceMicroserviceApplication to it then everything should work as expected.
If you don't follow Spring boot recommendation for package hierarchy then you need to explicitly specify packages to scan with #SpringBootApplication annotation.
Alright so none of the suggestions above worked, we were on the right path though.
Changing the structure as so worked:
There was also a pathing problem in the application.properties and thus I changed as so:
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}
To:
jdbc:mysql://localhost
And finally:
package com.braintobytes.finance.data.repository;
import org.springframework.data.repository.CrudRepository;
import com.braintobytes.finance.data.Currency;
public interface CurrencyRepository extends CrudRepository<Currency, Integer> {
}
Woah!
I'm trying to learn Spring Boot on my own. I use Maven and have created spring boot application with Tomcat container. When I use mvn spring-boot:run command to run the app it works fine. But when I start my app with ApplicationLoader class it gives me an error. Also, when I use ARC it gives me error 404 not found.
Of course, I understand that there's something wrong with my ApplicationLoader class, but I can't understand what exactly I should change to make it work. Your help is highly appreciated!
Application loader
package com.boris2barak.samplemvc.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class ApplicationLoader extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ApplicationLoader.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(ApplicationLoader.class, args);
}
}
Controller
package com.boris2barak.samplemvc.app;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class myFirstController {
#RequestMapping("/temperature")
public String whatIsTheWeather(Model model, #RequestParam(value="city", required=false, defaultValue="World") String city) {
model.addAttribute("city", city);
WeatherApp data = new WeatherApp();
return data.getTemperatureForCity(city);
}
}
Pom file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<groupId>com.boris2barak</groupId>
<artifactId>samplemvc</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.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.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
And the mistake looks like that:
objc[1937]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin/java (0x1043444c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/libinstru ment.dylib (0x1053b54e0). One of the two will be used. Which one is undefined.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.5.RELEASE)
2017-07-23 10:13:07.163 INFO 1937 --- [ main] c.b.samplemvc.app.ApplicationLoader : Starting ApplicationLoader on MBP-Boris with PID 1937 (/Users/boris/Java/samplemvc/target/classes started by boris in /Users/boris/Java/samplemvc)
2017-07-23 10:13:07.166 INFO 1937 --- [ main] c.b.samplemvc.app.ApplicationLoader : No active profile set, falling back to default profiles: default
2017-07-23 10:13:07.287 INFO 1937 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#16022d9d : startup date [Sun Jul 23 10:13:07 EEST 2017]; root of context hierarchy
2017-07-23 10:13:07.450 WARN 1937 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.boris2barak.samplemvc.app.ApplicationLoader]; nested exception is java.lang.IllegalStateException: Failed to introspect annotated methods on class org.springframework.boot.context.web.SpringBootServletInitializer
2017-07-23 10:13:07.487 ERROR 1937 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.boris2barak.samplemvc.app.ApplicationLoader]; nested exception is java.lang.IllegalStateException: Failed to introspect annotated methods on class org.springframework.boot.context.web.SpringBootServletInitializer
at org.springframework.context.annotation.ConfigurationClassParser.parse(Configuratio nClassParser.java:182) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConf igBeanDefinitions(ConfigurationClassPostProcessor.java:321) ~[spring-context- 4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcess BeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243) ~[spring-context- 4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDe finitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) ~ [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFa ctoryPostProcessors(PostProcessorRegistrationDelegate.java:98) ~[spring-context- 4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPo stProcessors(AbstractApplicationContext.java:678) ~[spring-context- 4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApp licationContext.java:520) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplicati on.java:361) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
at com.boris2barak.samplemvc.app.ApplicationLoader.main(ApplicationLoader.java:24) [classes/:na]
Caused by: java.lang.IllegalStateException: Failed to introspect annotated methods on class org.springframework.boot.context.web.SpringBootServletInitializer
at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(Stand ardAnnotationMetadata.java:163) ~[spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigura tionClass(ConfigurationClassParser.java:292) ~[spring-context- 4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurati onClass(ConfigurationClassParser.java:232) ~[spring-context- 4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.parse(Configuratio nClassParser.java:199) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.parse(Configuratio nClassParser.java:168) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
... 12 common frames omitted
Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletContext
at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_131]
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~ [na:1.8.0_131]
at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_131]
at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(Stand ardAnnotationMetadata.java:152) ~[spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
... 16 common frames omitted
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletContext
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_131]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_131]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~ [na:1.8.0_131]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_131]
... 20 common frames omitted
2017-07-23 10:13:07.502 INFO 1937 --- [ main] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/charsets.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/deploy.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/ cldrdata.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/dnsns.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/jaccess.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/jfxrt.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/localedata.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/nashorn.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/sunec.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/zipfs.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/javaws.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/jce.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/jfr.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/jfxswt.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/jsse.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/management-agent.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/plugin.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/resources.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/rt.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/ant-javafx.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/dt.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/javafx-mx.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/jconsole.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/packager.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/sa-jdi.jar, file:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/tools.jar, file:/Users/boris/Java/samplemvc/target/classes/, file:/Users/boris/.m2/repository/org/springframework/boot/spring-boot-starter-web/1.3.5.RELEASE/spring-boot-starter-web-1.3.5.RELEASE.jar, file:/Users/boris/.m2/repository/org/springframework/boot/spring-boot-starter/1.3.5.RELEASE/spring-boot-starter-1.3.5.RELEASE.jar, file:/Users/boris/.m2/repository/org/springframework/boot/spring-boot/1.3.5.RELEASE/spring-boot-1.3.5.RELEASE.jar, file:/Users/boris/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/1.3.5.RELEASE/spring-boot-autoconfigure-1.3.5.RELEASE.jar, file:/Users/boris/.m2/repository/org/springframework/boot/spring-boot-starter-logging/1.3.5.RELEASE/spring-boot-starter-logging-1.3.5.RELEASE.jar, file:/Users/boris/.m2/repository/ch/qos/logback/logback-classic/1.1.7/logback-classic-1.1.7.jar, file:/Users/boris/.m2/repository/ch/qos/logback/logback-core/1.1.7/logback-core-1.1.7.jar, file:/Users/boris/.m2/repository/org/slf4j/slf4j-api/1.7.21/slf4j-api-1.7.21.jar, file:/Users/boris/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.21/jcl-over-slf4j-1.7.21.jar, file:/Users/boris/.m2/repository/org/slf4j/jul-to-slf4j/1.7.21/jul-to-slf4j-1.7.21.jar, file:/Users/boris/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.21/log4j-over-slf4j-1.7.21.jar, file:/Users/boris/.m2/repository/org/springframework/spring-core/4.2.6.RELEASE/spring-core-4.2.6.RELEASE.jar, file:/Users/boris/.m2/repository/org/yaml/snakeyaml/1.16/snakeyaml-1.16.jar, file:/Users/boris/.m2/repository/org/springframework/boot/spring-boot-starter-validation/1.3.5.RELEASE/spring-boot-starter-validation-1.3.5.RELEASE.jar, file:/Users/boris/.m2/repository/org/hibernate/hibernate-validator/5.2.4.Final/hibernate-validator-5.2.4.Final.jar, file:/Users/boris/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar, file:/Users/boris/.m2/repository/org/jboss/logging/jboss-logging/3.3.0.Final/jboss-logging-3.3.0.Final.jar, file:/Users/boris/.m2/repository/com/fasterxml/classmate/1.1.0/classmate-1.1.0.jar, file:/Users/boris/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.6.6/jackson-databind-2.6.6.jar, file:/Users/boris/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.6.6/jackson-annotations-2.6.6.jar, file:/Users/boris/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.6.6/jackson-core-2.6.6.jar, file:/Users/boris/.m2/repository/org/springframework/spring-web/4.2.6.RELEASE/spring-web-4.2.6.RELEASE.jar, file:/Users/boris/.m2/repository/org/springframework/spring-aop/4.2.6.RELEASE/spring-aop-4.2.6.RELEASE.jar, file:/Users/boris/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/Users/boris/.m2/repository/org/springframework/spring-beans/4.2.6.RELEASE/spring-beans-4.2.6.RELEASE.jar, file:/Users/boris/.m2/repository/org/springframework/spring-context/4.2.6.RELEASE/spring-context-4.2.6.RELEASE.jar, file:/Users/boris/.m2/repository/org/springframework/spring-webmvc/4.2.6.RELEASE/spring-webmvc-4.2.6.RELEASE.jar, file:/Users/boris/.m2/repository/org/springframework/spring-expression/4.2.6.RELEASE/spring-expression-4.2.6.RELEASE.jar, file:/Users/boris/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/8.0.33/tomcat-embed-el-8.0.33.jar, file:/Users/boris/.m2/repository/com/google/code/gson/gson/2.6.2/gson-2.6.2.jar, file:/Users/boris/.m2/repository/commons-io/commons-io/2.5/commons-io-2.5.jar, file:/Applications/IntelliJ%20IDEA%20CE.app/Contents/lib/idea_rt.jar]
Process finished with exit code 1
From the stack trace it's clear that the problem is java.lang.NoClassDefFoundError: javax/servlet/ServletContext means the class is not in the CLASSPATH, which is present in the tomcat jars which is part of spring-boot-starter-tomcat dependencies.
So to make it work with spring boot standalone war/fat jar the spring-boot-starter-tomcat dependency should be in compile scope.
But if you want to deploy in to a java container like tomcat which will have the servlet classes in the container itself so you have keep the spring-boot-starter-tomcat in provided scope.
The best way to handle is create two maven profiles and in one keep the spring-boot-starter-tomcat in compile scope and in another profile in provided scope.
You need to change the SpringBoot main class ApplicationLoader with this class that provided
#SpringBootApplication(scanBasePackages = "com.boris2barak")
public class ApplicationLoader{
public static void main(String[] args) {
SpringApplication.run(ApplicationLoader.class, args);
}
}