Related
Given my Spring boot application code:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import com.couchbase.client.java.Bucket;
import net.javacrumbs.shedlock.provider.couchbase.javaclient3.CouchbaseLockProvider;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
#SpringBootApplication
#EnableScheduling
#EnableSchedulerLock(defaultLockAtMostFor = "10m")
public class MythoughtsApplication {
public static void main(String[] args) {
SpringApplication.run(MythoughtsApplication.class, args);
}
#Bean
public CouchbaseLockProvider lockProvider(Bucket bucket) {
return new CouchbaseLockProvider(bucket);
}
}
pom.xml
using the latest shedlock in the below pom.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.guru</groupId>
<artifactId>mythoughts</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mythoughts</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-couchbase</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
</dependency>
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>core-io</artifactId>
<version>2.3.1</version>
</dependency>
**<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
**<version>4.37.0</version>**
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-couchbase-javaclient3</artifactId>
**<version>4.37.0</version>**
</dependency>**
<dependency>
<groupId>com.unboundid</groupId>
<artifactId>unboundid-ldapsdk</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</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-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</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>
couchbase Connection file
#Configuration
public class CouchbaseConfig extends AbstractCouchbaseConfiguration {
#Override
public String getConnectionString() {
// TODO Auto-generated method stub
return "127.0.0.1";
}
#Override
public String getUserName() {
// TODO Auto-generated method stub
return "admin";
}
#Override
public String getPassword() {
// TODO Auto-generated method stub
return "1234";
}
#Override
public String getBucketName() {
// TODO Auto-generated method stub
return "admin";
}
}
controller file
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.guru.mythoughts.service.UserService;
import net.javacrumbs.shedlock.core.LockAssert;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
#RestController
public class UserController {
#Scheduled(cron = "*/5 * * * * *")
#SchedulerLock(name = "scheduledTaskName", lockAtMostFor = "PT5M", lockAtLeastFor = "PT4M")
public void scheduledTask() {
LockAssert.assertLocked();
System.out.println("cloked");
}
}
Output with error:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.0)
2022-06-21 17:36:01.346 INFO 21152 --- [ main] c.zzz.mythoughts.MyApplication : Starting MythoughtsApplication using Java 1.8.0_271 on DESKTOP-O8IM34ASBST with PID 21152 (C:\Users\G\Downloads\mythoughts\target\classes started by in C:\Users\G\Downloads\mythoughts)
2022-06-21 17:36:01.350 INFO 21152 --- [ main] c.zzz.mythoughts.MythoughtsApplication : No active profile set, falling back to 1 default profile: "default"
2022-06-21 17:36:01.889 INFO 21152 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Couchbase repositories in DEFAULT mode.
2022-06-21 17:36:02.033 INFO 21152 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 139 ms. Found 0 Couchbase repository interfaces.
2022-06-21 17:36:02.039 INFO 21152 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Couchbase repositories in DEFAULT mode.
2022-06-21 17:36:02.061 INFO 21152 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 22 ms. Found 1 Couchbase repository interfaces.
2022-06-21 17:36:02.504 INFO 21152 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-06-21 17:36:02.514 INFO 21152 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-06-21 17:36:02.514 INFO 21152 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.63]
2022-06-21 17:36:02.751 INFO 21152 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-06-21 17:36:02.751 INFO 21152 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1346 ms
2022-06-21 17:36:03.445 INFO 21152 --- [ cb-events] com.couchbase.core : [com.couchbase.core][CoreCreatedEvent] {"clientVersion":"3.3.0","clientGitHash":"${buildNumber}","coreVersion":"2.3.1","coreGitHash":"${buildNumber}","userAgent":"couchbase-java/3.3.0 (Windows 10 10.0 amd64; Java HotSpot(TM) 64-Bit Server VM 1.8.0_271-b09)","maxNumRequestsInRetry":32768,"ioEnvironment":{"nativeIoEnabled":true,"eventLoopThreadCount":4,"eventLoopGroups":["NioEventLoopGroup"]},"ioConfig":{"captureTraffic":[],"mutationTokensEnabled":true,"networkResolution":"auto","dnsSrvEnabled":true,"tcpKeepAlivesEnabled":true,"tcpKeepAliveTimeMs":60000,"configPollIntervalMs":2500,"kvCircuitBreakerConfig":"disabled","queryCircuitBreakerConfig":"disabled","viewCircuitBreakerConfig":"disabled","searchCircuitBreakerConfig":"disabled","analyticsCircuitBreakerConfig":"disabled","managerCircuitBreakerConfig":"disabled","eventingCircuitBreakerConfig":"disabled","backupCircuitBreakerConfig":"disabled","numKvConnections":1,"maxHttpConnections":12,"idleHttpConnectionTimeoutMs":4500,"configIdleRedialTimeoutMs":300000,"memcachedHashingStrategy":"StandardMemcachedHashingStrategy"},"compressionConfig":{"enabled":true,"minRatio":0.83,"minSize":32},"securityConfig":{"tlsEnabled":false,"nativeTlsEnabled":true,"hostnameVerificationEnabled":true,"trustCertificates":null,"trustManagerFactory":null,"ciphers":[]},"timeoutConfig":{"kvMs":2500,"kvDurableMs":10000,"managementMs":75000,"queryMs":75000,"viewMs":75000,"searchMs":75000,"analyticsMs":75000,"connectMs":10000,"disconnectMs":10000,"eventingMs":75000,"backupMs":75000},"loggerConfig":{"customLogger":null,"fallbackToConsole":false,"consoleLogLevel":{"name":"INFO","resourceBundleName":"sun.util.logging.resources.logging","localizedName":"INFO"},"consoleLoggerFormatter":"DefaultLoggerFormatter","disableSlf4j":false,"loggerName":"CouchbaseLogger","diagnosticContextEnabled":false},"orphanReporterConfig":{"emitIntervalMs":10000,"sampleSize":10,"queueLength":1024,"enabled":true},"thresholdLoggingTracerConfig":{"enabled":true,"emitIntervalMs":10000,"sampleSize":10,"queueLength":1024,"kvThresholdMs":500,"queryThresholdMs":1000,"searchThresholdMs":1000,"analyticsThresholdMs":1000,"viewThresholdMs":1000},"loggingMeterConfig":{"enabled":true,"emitIntervalMs":600000},"retryStrategy":"BestEffortRetryStrategy","requestTracer":"ThresholdLoggingTracer","meter":"LoggingMeter","numRequestCallbacks":0,"scheduler":"ParallelScheduler","schedulerThreadCount":8,"transactionsConfig":{"durabilityLevel":"MAJORITY","timeoutMs":15000,"cleanupConfig":{"runLostAttemptsCleanupThread":true,"runRegularAttemptsCleanupThread":true,"cleanupWindowMs":60000,"cleanupSet":""},"numAtrs":1024,"metadataCollection":"none","scanConsistency":"none"}} {"coreId":"0xa407cf8700000001","seedNodes":[{"address":"127.0.0.1"}]}
2022-06-21 17:36:03.445 INFO 21152 --- [ cb-events] com.couchbase.transactions : [com.couchbase.transactions][TransactionsStartedEvent] Transactions successfully initialised, regular cleanup enabled=true, lost cleanup enabled=true
2022-06-21 17:36:03.452 INFO 21152 --- [ cb-events] com.couchbase.node : [com.couchbase.node][NodeConnectedEvent] Node connected {"coreId":"0xa407cf8700000001","managerPort":"8091","remote":"127.0.0.1"}
2022-06-21 17:36:03.985 WARN 21152 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'lockProvider' defined in com.guru.mythoughts.MythoughtsApplication: Unsatisfied dependency expressed through method 'lockProvider' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.couchbase.client.java.Bucket' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2022-06-21 17:36:04.026 INFO 21152 --- [ cb-events] com.couchbase.transactions.cleanup : [com.couchbase.transactions.cleanup][LogEvent] Waiting for 1 regular background threads to exit
2022-06-21 17:36:04.027 INFO 21152 --- [ cb-events] c.c.transactions.cleanup.regular : [com.couchbase.transactions.cleanup.regular][LogEvent] Stopping background cleanup thread for transactions from this client
2022-06-21 17:36:04.027 INFO 21152 --- [ cb-events] com.couchbase.transactions.cleanup.lost : [com.couchbase.transactions.cleanup.lost][LogEvent] Client d9110 has been told to cancel
2022-06-21 17:36:04.027 INFO 21152 --- [ cb-events] com.couchbase.transactions.cleanup.lost : [com.couchbase.transactions.cleanup.lost][LogEvent] Client d9110 stopping lost cleanup process, 0 threads running
2022-06-21 17:36:04.027 INFO 21152 --- [ cb-events] com.couchbase.transactions.cleanup.lost : [com.couchbase.transactions.cleanup.lost][LogEvent] Client d9110 stopped lost cleanup process and removed client from client records
2022-06-21 17:36:04.027 INFO 21152 --- [ cb-events] com.couchbase.transactions.cleanup : [com.couchbase.transactions.cleanup][LogEvent] Background threads have exitted
2022-06-21 17:36:04.027 INFO 21152 --- [ cb-events] com.couchbase.node : [com.couchbase.node][NodeDisconnectedEvent][667us] Node disconnected {"coreId":"0xa407cf8700000001","managerPort":"8091","remote":"127.0.0.1"}
2022-06-21 17:36:04.027 INFO 21152 --- [ cb-events] com.couchbase.core : [com.couchbase.core][ShutdownCompletedEvent][19ms] Completed shutdown and closed all open buckets {"coreId":"0xa407cf8700000001"}
2022-06-21 17:36:04.118 INFO 21152 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-06-21 17:36:04.130 INFO 21152 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-06-21 17:36:04.157 ERROR 21152 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method lockProvider in com.guru.mythoughts.MythoughtsApplication required a bean of type 'com.couchbase.client.java.Bucket' that could not be found.
Action:
Consider defining a bean of type 'com.couchbase.client.java.Bucket' in your configuration.
I have given sample code and when I tried to run the application I am getting the above error. I have scheduled a method in controller and it should run for every 5 seconds.
I have followed the above in the given below link
https://gitcode.net/mirrors/lukas-krecan/ShedLock/-/tree/master/providers/couchbase
How can i solve this error?
Autowired the Cluster class and used the cluster to get the bucket details with bean creation in main class which return the bucket object. please see the same code and it is working fine.
#Autowired
Cluster cluster;
#Bean
public Bucket getBucket() {
return cluster.bucket("bucket");
}
}
Another option is to have a Cluster argument to your getBucket() bean method.
#Bean
public Bucket getBucket(Cluster cluster){
return cluster.bucket("myBucket");
}
I am trying to adapt the REST Controller example on the Spring Boot website.
Unfortunately I've got the following error when I am trying to access the localhost:8080/item URL.
{
"timestamp": 1436442596410,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/item"
}
POM:
<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>SpringBootTest</groupId>
<artifactId>SpringBootTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<javaVersion>1.8</javaVersion>
<mainClassPackage>com.nice.application</mainClassPackage>
<mainClass>${mainClassPackage}.InventoryApp</mainClass>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${javaVersion}</source>
<target>${javaVersion}</target>
</configuration>
</plugin>
<!-- Makes the Spring Boot app executable for a jar file. The additional configuration is needed for the cmd: mvn spring-boot:repackage
OR mvn spring-boot:run -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>${mainClass}</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Create a jar with a manifest -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<mainClass>${mainClass}</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot. This replaces the usage of the Spring Boot parent POM file. -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.2.5.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- more comfortable usage of several features when developing in an IDE. Developer tools are automatically disabled when
running a fully packaged application. If your application is launched using java -jar or if it’s started using a special classloader,
then it is considered a 'production application'. Applications that use spring-boot-devtools will automatically restart whenever files
on the classpath change. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
</dependencyManagement>
<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>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>15.0</version>
</dependency>
</dependencies>
</project>
Starter-Application:
package com.nice.application;
#SpringBootApplication // same as #Configuration #EnableAutoConfiguration #ComponentScan
public class InventoryApp {
public static void main( String[] args ) {
SpringApplication.run( InventoryApp.class, args );
}
}
REST-Controller:
package com.nice.controller;
#RestController // shorthand for #Controller and #ResponseBody rolled together
public class ItemInventoryController {
public ItemInventoryController() {
}
#RequestMapping( "/item" )
public String getStockItem() {
return "It's working...!";
}
}
I am building this project with Maven.
Started it as jar (spring-boot:run) and as well inside the IDE (Eclipse).
Console Log:
2015-07-09 14:21:52.132 INFO 1204 --- [ main] c.b.i.p.s.e.i.a.InventoryApp : Starting InventoryApp on 101010002016M with PID 1204 (C:\eclipse_workspace\SpringBootTest\target\classes started by MFE in C:\eclipse_workspace\SpringBootTest)
2015-07-09 14:21:52.165 INFO 1204 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#7a3d45bd: startup date [Thu Jul 09 14:21:52 CEST 2015]; root of context hierarchy
2015-07-09 14:21:52.661 INFO 1204 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2015-07-09 14:21:53.430 INFO 1204 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2015-07-09 14:21:53.624 INFO 1204 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2015-07-09 14:21:53.625 INFO 1204 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.23
2015-07-09 14:21:53.731 INFO 1204 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2015-07-09 14:21:53.731 INFO 1204 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1569 ms
2015-07-09 14:21:54.281 INFO 1204 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2015-07-09 14:21:54.285 INFO 1204 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2015-07-09 14:21:54.285 INFO 1204 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2015-07-09 14:21:54.508 INFO 1204 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#7a3d45bd: startup date [Thu Jul 09 14:21:52 CEST 2015]; root of context hierarchy
2015-07-09 14:21:54.573 INFO 1204 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2015-07-09 14:21:54.573 INFO 1204 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2015-07-09 14:21:54.594 INFO 1204 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-07-09 14:21:54.594 INFO 1204 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-07-09 14:21:54.633 INFO 1204 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-07-09 14:21:54.710 INFO 1204 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2015-07-09 14:21:54.793 INFO 1204 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2015-07-09 14:21:54.795 INFO 1204 --- [ main] c.b.i.p.s.e.i.a.InventoryApp : Started InventoryApp in 2.885 seconds (JVM running for 3.227)
2015-07-09 14:22:10.911 INFO 1204 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2015-07-09 14:22:10.911 INFO 1204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2015-07-09 14:22:10.926 INFO 1204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 15 ms
What I've tried so far:
Accessing the URL with the application name (InventoryApp)
Put another #RequestMapping("/") at class level of the ItemInventoryController
As far as I understood, I won't need an application-context when using Spring Boot. Am I right?
What else can I do to access the method via URL?
Try adding the following to your InventoryApp class
#SpringBootApplication
#ComponentScan(basePackageClasses = ItemInventoryController.class)
public class InventoryApp {
...
spring-boot will scan for components in packages below com.nice.application, so if your controller is in com.nice.controller you need to scan for it explicitly.
Adding to MattR's answer:
As stated in here, #SpringBootApplication automatically inserts the needed annotations: #Configuration, #EnableAutoConfiguration, and also #ComponentScan; however, the #ComponentScan will only look for the components in the same package as the App, in this case your com.nice.application, whereas your controller resides in com.nice.controller. That's why you get 404 because the App didn't find the controller in the application package.
Same 404 response I got after service executed with the below code
#Controller
#RequestMapping("/duecreate/v1.0")
public class DueCreateController {
}
Response:
{
"timestamp": 1529692263422,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/duecreate/v1.0/status"
}
after changing it to below code I received proper response
#RestController
#RequestMapping("/duecreate/v1.0")
public class DueCreateController {
}
Response:
{
"batchId": "DUE1529673844630",
"batchType": null,
"executionDate": null,
"status": "OPEN"
}
SpringBoot developers recommend to locate your main application class in a root package above other classes. Using a root package also allows the #ComponentScan annotation to be used without needing to specify a basePackage attribute. Detailed info
But be sure that the custom root package exists.
There are 2 method to overcome this
Place the bootup application at start of the package structure and rest all controller inside it.
Example :
package com.spring.boot.app; - You bootup application(i.e. Main Method -SpringApplication.run(App.class, args);)
You Rest Controller in with the same package structure
Example :
package com.spring.boot.app.rest;
Explicitly define the Controller in the Bootup package.
Method 1 is more cleaner.
I had this issue and what you need to do is fix your packages. If you downloaded this project from http://start.spring.io/ then you have your main class in some package. For example if the package for the main class is: "com.example" then and your controller must be in package: "com.example.controller". Hope this helps.
The controller should be accessible in the same namespace
This is what you have
This is how it should be, see the hierarchy of the namespace
You need to modify the Starter-Application class as shown below.
#SpringBootApplication
#EnableAutoConfiguration
#ComponentScan(basePackages="com.nice.application")
#EnableJpaRepositories("com.spring.app.repository")
public class InventoryApp extends SpringBootServletInitializer {..........
And update the Controller, Service and Repository packages structure as I mentioned below.
Example:
REST-Controller
package com.nice.controller; --> It has to be modified as
package com.nice.application.controller;
You need to follow proper package structure for all packages which are in Spring Boot MVC flow.
So, If you modify your project bundle package structures correctly then your spring boot app will work correctly.
Replace #RequestMapping( "/item" ) with #GetMapping(value="/item", produces=MediaType.APPLICATION_JSON_VALUE).
Maybe it will help somebody.
for me, I was adding spring-web instead of the spring-boot-starter-web into my pom.xml
when i replace it from spring-web to spring-boot-starter-web, all maping is shown in the console log.
I had exact same error, I was not giving base package. Giving correct base package,ressolved it.
package com.ymc.backend.ymcbe;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages="com.ymc.backend")
public class YmcbeApplication {
public static void main(String[] args) {
SpringApplication.run(YmcbeApplication.class, args);
}
}
Note: not including .controller
#ComponentScan(basePackages="com.ymc.backend.controller") because i
have many other component classes which my project does not scan if i
just give .controller
Here is my controller sample:
package com.ymc.backend.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#CrossOrigin
#RequestMapping(value = "/user")
public class UserController {
#PostMapping("/sendOTP")
public String sendOTP() {
return "OTP sent";
};
}
I found a really great thread for this issue.
https://coderanch.com/t/735307/frameworks/Spring-boot-Rest-api
The controller api should be in the sub directory structure to automatically detect the controllers. Otherwise annotation argument can be used.
#SpringBootApplication(scanBasePackages = {"com.example.demo", "com.example.Controller"})
Sometimes spring boot behaves weird. I specified below in application class and it works:
#ComponentScan("com.seic.deliveryautomation.controller")
I got the 404 problem, because of Url Case Sensitivity.
For example
#RequestMapping(value = "/api/getEmployeeData",method = RequestMethod.GET) should be accessed using http://www.example.com/api/getEmployeeData. If we are using http://www.example.com/api/getemployeedata, we'll get the 404 error.
Note:
http://www.example.com is just for reference which i mentioned above. It should be your domain name where you hosted your application.
After a lot of struggle and apply all the other answers in this post, I got that the problem is with that url only. It might be silly problem. But it cost my 2 hours. So I hope it will help someone.
It also works if we use as follows:
#SpringBootApplication(scanBasePackages = { "<class ItemInventoryController package >.*" })
It could be that something else is running on port 8080, and you're actually connecting to it by mistake.
Definitely check that out, especially if you have dockers that are bringing up other services you don't control, and are port forwarding those services.
The problem is with your package structure. Spring Boot Application has a specific package structure to allow spring context to scan and load various beans in its context.
In com.nice.application is where your Main Class is and in com.nice.controller, you have your controller classes.
Move your com.nice.controller package into com.nice.application so that Spring can access your beans.
Another solution in case it helps: in my case, the problem was that I had a #RequestMapping("/xxx") at class level (in my controller), and in the exposed services I had #PostMapping (value = "/yyyy") and #GetMapping (value = "/zzz"); once I commented the #RequestMapping("/xxx") and managed all at method level, worked like a charm.
For me, the problem was that I had set up the Application in a way that it always immediately shut down after starting. So by the time I tried out if I could access the controller, the Application wasn't running anymore.
The problem with immediately shutting down is adressed in this thread.
#SpringBootApplication
#ComponentScan(basePackages = {"com.rest"}) // basePackageClasses = HelloController.class)
// use above componnent scan to add packages
public class RestfulWebServicesApplication {
public static void main(String[] args) {
SpringApplication.run(RestfulWebServicesApplication.class, args);
}
}
There may 3 reasons causing for this error:
1>
check your URL you are requesting is correct
2> check if your
using MVC then use #Controller else use #RestController
3> check
whether you have placed Controller package(or Class) outside the root
package example: com.example.demo -> is your main
package
place controller package inside com.example.demo.controller
I had the same issue, because I created an inner class annotated with #Configuration and it prohibited somehow the component scan.
I had the same problem, and while the above solution are correct in their own right, they did not work for me, and I found another possible reason that solved it - you have to shut down the application from the port, and restart your application, if doing a Maven Update or a project clean fail to solve it.
Briefly, open a command prompt, and run the following two commands:
netstat -ano | findstr :8080
This command will locate the Process ID that is attached at the port that your app is running on - please make sure to specify the port, if you have it anywhere other than the default.
You will get the following output:
What you care about is the number in the last column, which is the process ID associated with the port, on which the instance of the app is running.
If you are using STS4 for your development purposes, you can also see the PID on the top margin of the console, but you do have to squint for it:
At this point, run the next command to kill the process:
taskkill /pid 22552 /f
And it results in this:
Do remember that there will be a different PID for every time you run the application.
And finally, you can run it again, and that should do it.
More relevant materials:
Closing network connections
Programmatically shutting down SpringBoot app
New to Springboot, tried everything above, but ended up being as simple as I had a / at the end of the URL on my browser while my only Get() method was blank, just returning a string.
Hope this'll help someone someday.
Change the Return type from String to ResponseEntity
Like :
#RequestMapping( "/item" )
public ResponseEntity<String> getStockItem() {
return new ResponseEntity<String>("It's working...!", HttpStatus.OK);
}
Place your springbootapplication class in root package for example if your service,controller is in springBoot.xyz package then your main class should be in springBoot package otherwise it will not scan below packages
You can add inside the POM.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>XXXXXXXXX</version>
</dependency>
I am building an app with JWT security but it keeps ignoring my rest controllers, and not registering the APIs:
Here is my pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 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.0</version>
<relativePath/>
</parent>
<groupId>org.home</groupId>
<artifactId>testapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>testapp</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.3</version>
</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.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- SECURITY -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Here is my application.yml
...
server:
url: https://localhost:8443
port: 8443
ssl:
enabled: true
key-store: classpath:keystore/my_keystore.p12
key-store-password: mySuperPassword#
key-store-type: pkcs12
key-alias: mykey
Here is my main class :
package org.home.mysecurityapplication;
#SpringBootApplication(scanBasePackages={"org.home.**"})
public class MySecureApplication {
public static void main(String[] args) {
SpringApplication.run(MySecureApplication.class, args);
}
}
Here is my web initializer :
package org.home.mysecurityapplication.configuration;
public class WebInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext sc) {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.setConfigLocations("org.home.**");
rootContext.refresh();
rootContext.setServletContext(sc);
sc.addListener(new ContextLoaderListener(rootContext));
ServletRegistration.Dynamic apiSR = sc.addServlet("api-dispatcher", new DispatcherServlet(rootContext));
apiSR.setLoadOnStartup(1);
apiSR.addMapping("/");
}
}
Here i am evabling mvc :
package org.home.mysecurityapplication.configuration;
#Configuration
#ComponentScan(basePackages={"org.home.**"})
#EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
}
Here is my security configurer adapter:
package org.home.mysecurityapplication.security;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private final MyAuthenticationProvider myAuthenticationProvider;
private final CredentialsFilter credentialsFilter;
#Autowired
public MyWebSecurityConfigurerAdapter(MyAuthenticationProvider myAuthenticationProvider, CredentialsFilter credentialsFilter) {
this.myAuthenticationProvider = myAuthenticationProvider;
this.credentialsFilter = credentialsFilter;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.POST, "/roles").permitAll() // everyone should access login-api
;
// disable csrf
http.csrf().disable();
// app session is stateless
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(credentialsFilter, UsernamePasswordAuthenticationFilter.class);
http.requiresChannel(channel -> channel.anyRequest().requiresSecure());
}
#Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.eraseCredentials(false)
.authenticationProvider(myAuthenticationProvider);
}
}
Here is my controller:
package org.home.mysecurityapplication.security.controller;
#RestController
#RequestMapping(value="")
public class SecurityController {
#Autowired
private SecurityService securityServiceImpl;
private static final Logger logger = LoggerFactory.getLogger(SecurityController.class);
#RequestMapping(value = "/roles", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.TEXT_PLAIN_VALUE)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody
String generateToken(#RequestBody CredentialsDTO credentials) throws MyRestPreconditionsException {
logger.debug("User "+credentials.getUsername()+" logging in ...");
String token = securityServiceImpl.generateTokenForUser(credentials);
logger.debug("User "+credentials.getUsername()+" log in successfull.");
return token;
}
}
As you can see, rest controller /roles does not register :(
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.0)
2022-02-15 22:37:37.906 INFO 10720 --- [ main] l.h.myapp.MySecurityApplication : Starting MySecurityApplication using Java 17.0.2 on HAL-9015 with PID 10720 (C:\Users\Lazaruss\IdeaProjects\greenhealth2\target\classes started by Lazaruss in C:\Users\Lazaruss\IdeaProjects\greenhealth2)
2022-02-15 22:37:37.909 INFO 10720 --- [ main] l.h.myapp.MySecurityApplication : No active profile set, falling back to default profiles: default
2022-02-15 22:37:38.629 INFO 10720 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-02-15 22:37:38.712 INFO 10720 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 68 ms. Found 1 JPA repository interfaces.
2022-02-15 22:37:39.879 INFO 10720 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8443 (https)
2022-02-15 22:37:39.894 INFO 10720 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-02-15 22:37:39.894 INFO 10720 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.55]
2022-02-15 22:37:40.036 INFO 10720 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-02-15 22:37:40.036 INFO 10720 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2067 ms
2022-02-15 22:37:40.330 INFO 10720 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-02-15 22:37:40.406 INFO 10720 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.1.Final
2022-02-15 22:37:40.652 INFO 10720 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-02-15 22:37:41.061 INFO 10720 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2022-02-15 22:37:41.840 INFO 10720 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-02-15 22:37:41.851 INFO 10720 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-02-15 22:37:42.435 WARN 10720 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-02-15 22:37:42.957 INFO 10720 --- [ main] o.s.s.w.a.c.ChannelProcessingFilter : Validated configuration attributes
2022-02-15 22:37:42.959 INFO 10720 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.access.channel.ChannelProcessingFilter#7af0693b, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#110318a7, org.springframework.security.web.context.SecurityContextPersistenceFilter#265c0752, org.springframework.security.web.header.HeaderWriterFilter#3c9cfcde, org.springframework.security.web.authentication.logout.LogoutFilter#2e5c7cd5, lazaruss.home.myapp.security.CredentialsFilter#6dc2e473, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#7a75183d, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#6f695077, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#42ac309, org.springframework.security.web.session.SessionManagementFilter#799fc4c9, org.springframework.security.web.access.ExceptionTranslationFilter#34fcc5e3, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#152dbf8e]
2022-02-15 22:37:43.681 INFO 10720 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8443 (https) with context path ''
2022-02-15 22:37:43.690 INFO 10720 --- [ main] l.h.myapp.MySecurityApplication : Started MySecurityApplication in 6.437 seconds (JVM running for 7.137)
2022-02-15 22:37:49.009 INFO 10720 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
I suspect you are having a problem with the scanned packages.
#SpringBootApplication encapsulates #Configuration, #EnableAutoConfiguration, and #ComponentScan annotations with their default attributes. The default value for #ComponentScan means that all the sub packages on the package the #ComponentScan is used are scanned. That is why it is usually a good practice to include the main class in the base package of the project, so please make sure it is located there.
Having written this, try the following (drop scanBasePackages attribute and #ComponentScan annotation):
#SpringBootApplication
public class MySecureApplication {
public static void main(String[] args) {
SpringApplication.run(MySecureApplication.class, args);
}
}
#Configuration
#EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
}
I built a simple app with Spring Boot.
Test.java
package Test;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.scheduling.annotation.*;
#SpringBootApplication
#EnableScheduling
public class App
{
public static void main( String[] args )
{
SpringApplication.run (App.class, args);
}
}
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>Test</groupId>
<artifactId>Test</artifactId>
<version>1.0</version>
<name>Test</name>
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.4.0</version>
<configuration>
<fork>true</fork>
<mainClass>${start-class}</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Starts as expected.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.0.RELEASE)
2021-01-22 21:10:08.438 INFO 11932 --- [ main] Test.App : Starting App on ASPIRE with PID 11932 (/MvnTest/Test/target/classes started by ch in /data/projects/MvnTest/Test)
2021-01-22 21:10:08.441 INFO 11932 --- [ main] Test.App : No active profile set, falling back to default profiles: default
2021-01-22 21:10:09.421 INFO 11932 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-01-22 21:10:09.432 INFO 11932 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-01-22 21:10:09.432 INFO 11932 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.27]
2021-01-22 21:10:09.496 INFO 11932 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-01-22 21:10:09.496 INFO 11932 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 981 ms
2021-01-22 21:10:09.679 INFO 11932 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-01-22 21:10:09.820 INFO 11932 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: b1d1aca3-b55e-4d71-aac6-9e33e4d082bd
2021-01-22 21:10:09.889 INFO 11932 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#5a0bef24, org.springframework.security.web.context.SecurityContextPersistenceFilter#1bb740f2, org.springframework.security.web.header.HeaderWriterFilter#29fa6b65, org.springframework.security.web.csrf.CsrfFilter#3ac3f6f, org.springframework.security.web.authentication.logout.LogoutFilter#51b01550, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#3289079a, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#672a1c62, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#6468a7b6, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#708f018e, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#61f6d381, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#5f95f1e1, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#2f860823, org.springframework.security.web.session.SessionManagementFilter#47406941, org.springframework.security.web.access.ExceptionTranslationFilter#6504a875, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#1d247525]
2021-01-22 21:10:09.903 INFO 11932 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'taskScheduler'
2021-01-22 21:10:09.953 INFO 11932 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-01-22 21:10:09.957 INFO 11932 --- [ main] Test.App : Started App in 1.876 seconds (JVM running for 2.209)
I try to add a dependency for LDAP.
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
Then it terminates immediately.
21:05:32.453 [background-preinit] DEBUG org.jboss.logging - Logging Provider: org.jboss.logging.Log4j2LoggerProvider
21:05:32.456 [background-preinit] INFO org.hibernate.validator.internal.util.Version - HV000001: Hibernate Validator 6.0.17.Final
21:05:32.463 [background-preinit] DEBUG org.hibernate.validator.internal.engine.resolver.TraversableResolvers - Cannot find javax.persistence.Persistence on classpath. Assuming non JPA 2 environment. All properties will per default be traversable.
21:05:32.465 [background-preinit] DEBUG org.hibernate.validator.internal.xml.config.ValidationXmlParser - Trying to load META-INF/validation.xml for XML based Validator configuration.
21:05:32.466 [background-preinit] DEBUG org.hibernate.validator.internal.xml.config.ResourceLoaderHelper - Trying to load META-INF/validation.xml via TCCL
21:05:32.466 [background-preinit] DEBUG org.hibernate.validator.internal.xml.config.ResourceLoaderHelper - Trying to load META-INF/validation.xml via Hibernate Validator's class loader
21:05:32.467 [background-preinit] DEBUG org.hibernate.validator.internal.xml.config.ValidationXmlParser - No META-INF/validation.xml found. Using annotation based configuration only.
21:05:32.551 [background-preinit] DEBUG org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator - Loaded expression factory via original TCCL
21:05:32.555 [background-preinit] DEBUG org.hibernate.validator.internal.engine.ValidatorFactoryImpl - HV000234: Using org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator as ValidatorFactory-scoped message interpolator.
21:05:32.555 [background-preinit] DEBUG org.hibernate.validator.internal.engine.ValidatorFactoryImpl - HV000234: Using org.hibernate.validator.internal.engine.resolver.TraverseAllTraversableResolver as ValidatorFactory-scoped traversable resolver.
21:05:32.555 [background-preinit] DEBUG org.hibernate.validator.internal.engine.ValidatorFactoryImpl - HV000234: Using org.hibernate.validator.internal.util.ExecutableParameterNameProvider as ValidatorFactory-scoped parameter name provider.
21:05:32.555 [background-preinit] DEBUG org.hibernate.validator.internal.engine.ValidatorFactoryImpl - HV000234: Using org.hibernate.validator.internal.engine.DefaultClockProvider as ValidatorFactory-scoped clock provider.
21:05:32.555 [background-preinit] DEBUG org.hibernate.validator.internal.engine.ValidatorFactoryImpl - HV000234: Using org.hibernate.validator.internal.engine.scripting.DefaultScriptEvaluatorFactory as ValidatorFactory-scoped script evaluator factory.
Any ideas how to make it start normally?
I suspect you are have version number clashing.
when creating a spring boot project i suggest you use the spring boot initializer. Here you can select what dependencies you want. Then they generate a project for you and when you look into the pom, you will se that there is a parent pom declared at the top.
That usually looks like this and contains the version for that release of spring boot:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
</parent>
This parent is essential because spring boot is a framework, so each release of the framework includes dependencies with specific version numbers. The parent pom makes sure that all the dependencies are of version numbers that work together. You can read about how a java project in spring is setup here.
Which also means that when you declare other spring dependencies you can omit the
version numbers, since the parent pom will pick a version number that works well with that version of spring boot.
// no need for version numbering it gets fetched from the parent
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
So when you declare the ldap dependency you can also omit the version number.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-ldap</artifactId>
</dependency>
But as mentioned in the top, use the initializer to create a spring boot project. Super easy.
While creating a spring boot application on Spring boot 1.5.9, I am getting below error message. Can any body please help? Thanks in advance.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.9.RELEASE)
2018-01-26 22:16:01.534 INFO 7176 --- [ main] com.myapp.MyAppApplication : Starting MyAppApplication on DESKTOP-29H8ALN with PID 7176 (F:\My_SpringBoot_WorkSpace_20_01_2018\MyApp\MyApp\target\classes started by Tanmoy in F:\My_SpringBoot_WorkSpace_20_01_2018\MyApp\MyApp)
2018-01-26 22:16:01.534 INFO 7176 --- [ main] com.myapp.MyAppApplication : No active profile set, falling back to default profiles: default
2018-01-26 22:16:01.590 INFO 7176 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#61009542: startup date [Fri Jan 26 22:16:01 IST 2018]; root of context hierarchy
2018-01-26 22:16:02.889 INFO 7176 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 9001 (http)
2018-01-26 22:16:02.903 INFO 7176 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-01-26 22:16:02.904 INFO 7176 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
2018-01-26 22:16:03.075 INFO 7176 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-01-26 22:16:03.075 INFO 7176 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1490 ms
2018-01-26 22:16:03.238 INFO 7176 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-01-26 22:16:03.242 INFO 7176 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-01-26 22:16:03.243 INFO 7176 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-01-26 22:16:03.243 INFO 7176 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-01-26 22:16:03.243 INFO 7176 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-01-26 22:16:03.277 WARN 7176 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerController': Unsatisfied dependency expressed through field 'customerService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerService': Unsatisfied dependency expressed through field 'customersRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.myapp.repository.CustomersRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2018-01-26 22:16:03.278 INFO 7176 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-01-26 22:16:03.311 INFO 7176 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-01-26 22:16:03.396 ERROR 7176 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field customersRepository in com.myapp.service.CustomerService required a bean of type 'com.myapp.repository.CustomersRepository' that could not be found.
Action:
Consider defining a bean of type 'com.myapp.repository.CustomersRepository' in your configuration.
I am using this settings:
Spring Boot 1.5.9
Oracle 11g database.
Please find the below classes I am using along with the pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tanmoy</groupId>
<artifactId>MyApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MyApp</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<artifactId>hibernate-entitymanager</artifactId>
<groupId>org.hibernate</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>12.1.0.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Java code - application:
package com.myapp;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.myapp.entity.Customers;
import com.myapp.repository.CustomersRepository;
import com.myapp.service.CustomerService;
#SpringBootApplication
public class MyAppApplication {
public static void main(String[] args) {
SpringApplication.run(MyAppApplication.class, args);
}
#Bean
public CommandLineRunner demo(CustomersRepository repository) {
return (args) -> {
// fetch all customers
for (Customers customer : repository.findAll()) {
}
};
}
}
Java code - repository:
package com.myapp.repository;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.myapp.entity.Customers;
#Repository
public interface CustomersRepository extends CrudRepository<Customers, Integer> {
#Query("select * from customers")
public List<Customers> getAllCustomerts();
}
Java code - service:
package com.myapp.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.myapp.repository.CustomersRepository;
#Service
public class CustomerService {
#Autowired
CustomersRepository customersRepository;
public void getAllCustomers() {
System.out.println(customersRepository.findAll());
}
}
Remove the #Repository annotation from CustomersRepository.
The interface CrudRepository is already registered in Spring's container and it can be injected already (also its child interfaces).
I think there is more in the exception stacktrace which was not shared, I think exception will point to incorrect query. The query in CustomersRespository should be like below:
#Query("select c from Customers c")
public List<Customers> getAllCustomerts();
Why are you defining a getAllCustomers in the repository if you never use it?
The CrudRepository already gives you for free some useful method implementations without you having to write a single line of code besides the interface declaration.
My suggestion is to remove the getAllCustumers in repository and call findAll on the repository from the service.
#Autowired
CustomersRepository customersRepository;
This is not the proper way to Autowire. This is:
CustomersRepository customersRepository;
#Autowire
public defaultConstructor(CustomerRepository customerRepository){
this.customerRepository = customerRepository;
}
note: defaultConstructor is simply your class name (default constructor).