I'm learning Apache Camel in Spring Boot project and I try to create a Retful Webservice and the service is starting but the problem is that I get 404 when I call the endpoint.
#Component
#RequiredArgsConstructor
public class RestJavaDsl extends RouteBuilder {
private final WeatherDataProvider weatherDataProvider;
#Override
public void configure() throws Exception {
from("rest:get:javadsl/weather/{city}?produces=application/json")
.outputType(WeatherDto.class)
.process(this::getWeatherData);
}
private void getWeatherData(Exchange exchange) {
String city = exchange.getMessage().getHeader("city", String.class);
WeatherDto currentWeather = weatherDataProvider.getCurrentWeather(city);
Message message = new DefaultMessage(exchange.getContext());
message.setBody(currentWeather);
exchange.setMessage(message);
}
}
I created this class to hardcode some data:
#Component
public class WeatherDataProvider {
private static Map<String, WeatherDto> weatherData = new HashMap<>();
public WeatherDataProvider() {
WeatherDto dto = WeatherDto.builder().city("London").temp("10").unit("C").receivedTime(new Date().toString()).id(1).build();
weatherData.put("LONDON", dto);
}
public WeatherDto getCurrentWeather(String city) {
return weatherData.get(city.toUpperCase());
}
public void setCurrentWeather(WeatherDto dto) {
dto.setReceivedTime(new Date().toString());
weatherData.put(dto.getCity().toUpperCase(), dto);
}
}
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
public class WeatherDto implements Serializable {
static int counter = 1;
private int id = counter++;
private String city;
private String temp;
private String unit;
private String receivedTime;
}
application.yml
camel:
component:
servlet:
mapping:
context-path: /services/*
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.dgs</groupId>
<artifactId>camel-rest-springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>camel-rest-springboot</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<camel.version>3.14.0</camel.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test</artifactId>
<scope>test</scope>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jackson</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jaxb</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-servlet</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-servlet-starter</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-rest-starter</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The serviceis starting and this is the console log:
2022-01-24 20:01:40.353 INFO 15796 --- [ main] c.d.c.CamelRestSpringbootApplication : Starting CamelRestSpringbootApplication using Java 11.0.5 on pc-PC with PID 15796 (D:\Spring Boot\camel-rest-springboot\target\classes started by pc in D:\Spring Boot\camel-rest-springboot)
2022-01-24 20:01:40.357 INFO 15796 --- [ main] c.d.c.CamelRestSpringbootApplication : No active profile set, falling back to default profiles: default
2022-01-24 20:01:43.583 INFO 15796 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-01-24 20:01:43.604 INFO 15796 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-01-24 20:01:43.604 INFO 15796 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-01-24 20:01:43.820 INFO 15796 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-01-24 20:01:43.821 INFO 15796 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3235 ms
2022-01-24 20:01:45.228 INFO 15796 --- [ main] o.a.c.c.s.CamelHttpTransportServlet : Initialized CamelHttpTransportServlet[name=CamelServlet, contextPath=]
2022-01-24 20:01:45.233 INFO 15796 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-01-24 20:01:45.592 INFO 15796 --- [ main] o.a.c.impl.engine.AbstractCamelContext : Message DataType is enabled on CamelContext: camel-1
2022-01-24 20:01:45.607 INFO 15796 --- [ main] o.a.c.impl.engine.AbstractCamelContext : Routes startup (total:1 started:1)
2022-01-24 20:01:45.607 INFO 15796 --- [ main] o.a.c.impl.engine.AbstractCamelContext : Started route1 (rest://get:javadsl/weather/%7Bcity%7D)
2022-01-24 20:01:45.607 INFO 15796 --- [ main] o.a.c.impl.engine.AbstractCamelContext : Apache Camel 3.14.0 (camel-1) started in 370ms (build:83ms init:269ms start:18ms)
2022-01-24 20:01:45.617 INFO 15796 --- [ main] c.d.c.CamelRestSpringbootApplication : Started CamelRestSpringbootApplication in 6.569 seconds (JVM running for 8.087)
But when I try to call the endpoint http://localhost:8080/services/javadsl/weather/london
It looks like this endpoint doesn't exist, the rest isn't created. I used debugger and the method getWeatherData() isn't called.
And I think this log is not ok: Started route1 (rest://get:javadsl/weather/%7Bcity%7D), it should be something like that: route1 started and consuming from servlet:/javadsl/weather/%7Bcity%7D
And the tutorial is from here: https://www.youtube.com/watch?v=spDjbC8mZf0&t=433s
Thank you in advance!
You can start by creating example project using official camel-archetype-spring-boot maven archetype. You can generate project based on the archetype using your IDE or from command-line using following maven command.
mvn archetype:generate -DarchetypeArtifactId="camel-archetype-spring-boot" -DarchetypeGroupId="org.apache.camel.archetypes" -DarchetypeVersion="3.14.0"
Now in the maven project file pom.xml add following block to the dependencies
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-jetty-starter</artifactId>
</dependency>
Note that version doesn't need to be specified as it is provided by camel-spring-boot-dependencies BOM (bill of materials) in dependencyManagement section.
After that you can create new file ConfigureCamelContext.java where we can configure our CamelContext and provide it with RestConfiguration. We can do this by implementing CamelContextConfiguration and #Component annotation.
The annotation tells spring-framework that it should create instance of the class and inject it to objects that request it based on its class-type or interface. Camel is configured to automatically ask spring-framework for these RestConfiguration instances which it will proceed to use configure CamelContext.
package com.example;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spring.boot.CamelContextConfiguration;
import org.springframework.stereotype.Component;
#Component
public class ConfigureCamelContext implements CamelContextConfiguration {
#Override
public void beforeApplicationStart(CamelContext camelContext) {
RestConfiguration restConfiguration = new RestConfiguration();
restConfiguration.setApiComponent("jetty");
restConfiguration.setApiHost("localhost");
restConfiguration.setPort(8081);
camelContext.setRestConfiguration(restConfiguration);
}
#Override
public void afterApplicationStart(CamelContext camelContext) {
}
}
This should work with RestDSL and rest-component.
Edit MySpringBootRouter.java to something like this:
package com.example;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
#Component
public class MySpringBootRouter extends RouteBuilder {
static final String CONTET_TYPE_TEXT = "text/plain";
#Override
public void configure() {
rest()
.get("/hello/")
.route()
.setHeader(Exchange.CONTENT_TYPE, constant(CONTET_TYPE_TEXT))
.setBody().constant("Hello world")
.end()
.endRest()
.get("/hello/{name}")
.route()
.setHeader(Exchange.CONTENT_TYPE, constant(CONTET_TYPE_TEXT))
.setBody().simple("Hello ${headers.name}")
.end()
.endRest();
from("rest:get:test?produces=plain/text")
.setBody().constant("Hello from JavaDSL");
}
}
Comment out the class under src/test/java/<grouId>/ as the example test provided by the archetype is not applicable for for MySpringBootRouter and will interrupt build.
To run the project you can use command
mvn spring-boot:run
Now you should be able to open up localhost:8081/hello, localhost:8081/hello/<Name> or localhost:8081/test get response in plain text.
Related
I was using a tutorial and everything was working fine until I started dealing with swagger 2 dependencies.
I wonder now if there is a way to fix this.
SwaggerConfig:
package com.animes.apirest.config;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import static springfox.documentation.builders.PathSelectors.regex;
import java.util.ArrayList;
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket atividadeApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.atividades.apirest"))
.paths(regex("/api.*"))
.build()
.apiInfo(metaInfo());
}
private ApiInfo metaInfo() {
ApiInfo apiInfo = new ApiInfo(
"Atividades API REST",
"API REST de cadastro de atividades.",
"1.0",
"Terms of Service",
new Contact("João VR", "www.una.br/",
" "),
"Apache License Version 2.0",
"https://www.apache.org/licesen.html", new ArrayList<VendorExtension>()
);
return apiInfo;
}
}
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.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.animes</groupId>
<artifactId>apirest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apirest</name>
<description>Anime project for Spring Boot</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</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>20.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Error:
19:07:08.137 [Thread-0] DEBUG org.springframework.boot.devtools.restart.classloader.RestartClassLoader - Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader#43899316
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.0)
2021-11-21 19:07:08.606 INFO 9840 --- [ restartedMain] com.animes.apirest.ApirestApplication : Starting ApirestApplication using Java 16.0.2 on DESKTOP-TIGCP3C with PID 9840 (C:\Program Files (x86)\eclipse\Workspace\apirest\target\classes started by Pichau in C:\Program Files (x86)\eclipse\Workspace\apirest)
2021-11-21 19:07:08.607 INFO 9840 --- [ restartedMain] com.animes.apirest.ApirestApplication : No active profile set, falling back to default profiles: default
2021-11-21 19:07:08.679 INFO 9840 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-11-21 19:07:08.680 INFO 9840 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-11-21 19:07:09.807 INFO 9840 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-11-21 19:07:09.895 INFO 9840 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 71 ms. Found 1 JPA repository interfaces.
2021-11-21 19:07:10.790 INFO 9840 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-11-21 19:07:10.813 INFO 9840 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-11-21 19:07:10.813 INFO 9840 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.55]
2021-11-21 19:07:10.965 INFO 9840 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-11-21 19:07:10.966 INFO 9840 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2286 ms
2021-11-21 19:07:11.194 INFO 9840 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-11-21 19:07:11.245 INFO 9840 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.1.Final
2021-11-21 19:07:11.427 INFO 9840 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-11-21 19:07:11.536 INFO 9840 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-11-21 19:07:11.746 INFO 9840 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-11-21 19:07:11.776 INFO 9840 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
2021-11-21 19:07:12.466 INFO 9840 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-11-21 19:07:12.475 INFO 9840 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-11-21 19:07:13.074 WARN 9840 --- [ restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-11-21 19:07:13.266 INFO 9840 --- [ restartedMain] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [springfox.documentation.swagger2.web.Swagger2Controller#getDocumentation(String, HttpServletRequest)]
2021-11-21 19:07:13.497 INFO 9840 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-11-21 19:07:13.717 INFO 9840 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-11-21 19:07:13.718 INFO 9840 --- [ restartedMain] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2021-11-21 19:07:13.740 INFO 9840 --- [ restartedMain] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2021-11-21 19:07:13.744 WARN 9840 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.toString()" because the return value of "springfox.documentation.spi.service.contexts.Orderings.patternsCondition(springfox.documentation.RequestHandler)" is null
2021-11-21 19:07:13.747 INFO 9840 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-11-21 19:07:13.751 INFO 9840 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-11-21 19:07:13.760 INFO 9840 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2021-11-21 19:07:13.782 INFO 9840 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-11-21 19:07:13.796 INFO 9840 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-11-21 19:07:13.826 ERROR 9840 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.toString()" because the return value of "springfox.documentation.spi.service.contexts.Orderings.patternsCondition(springfox.documentation.RequestHandler)" is null
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.13.jar:5.3.13]
at java.base/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na]
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1290) ~[spring-boot-2.6.0.jar:2.6.0]
at com.animes.apirest.ApirestApplication.main(ApirestApplication.java:10) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.6.0.jar:2.6.0]
Caused by: java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.toString()" because the return value of "springfox.documentation.spi.service.contexts.Orderings.patternsCondition(springfox.documentation.RequestHandler)" is null
at springfox.documentation.spi.service.contexts.Orderings$8.compare(Orderings.java:112) ~[springfox-spi-2.9.2.jar:null]
at springfox.documentation.spi.service.contexts.Orderings$8.compare(Orderings.java:109) ~[springfox-spi-2.9.2.jar:null]
at com.google.common.collect.ComparatorOrdering.compare(ComparatorOrdering.java:37) ~[guava-20.0.jar:na]
at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[na:na]
at java.base/java.util.TimSort.sort(TimSort.java:220) ~[na:na]
at java.base/java.util.Arrays.sort(Arrays.java:1232) ~[na:na]
at com.google.common.collect.Ordering.sortedCopy(Ordering.java:855) ~[guava-20.0.jar:na]
at springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider.requestHandlers(WebMvcRequestHandlerProvider.java:57) ~[springfox-spring-web-2.9.2.jar:null]
at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper$2.apply(DocumentationPluginsBootstrapper.java:138) ~[springfox-spring-web-2.9.2.jar:null]
at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper$2.apply(DocumentationPluginsBootstrapper.java:135) ~[springfox-spring-web-2.9.2.jar:null]
at com.google.common.collect.Iterators$7.transform(Iterators.java:750) ~[guava-20.0.jar:na]
at com.google.common.collect.TransformedIterator.next(TransformedIterator.java:47) ~[guava-20.0.jar:na]
at com.google.common.collect.TransformedIterator.next(TransformedIterator.java:47) ~[guava-20.0.jar:na]
at com.google.common.collect.MultitransformedIterator.hasNext(MultitransformedIterator.java:52) ~[guava-20.0.jar:na]
at com.google.common.collect.MultitransformedIterator.hasNext(MultitransformedIterator.java:50) ~[guava-20.0.jar:na]
at com.google.common.collect.ImmutableList.copyOf(ImmutableList.java:249) ~[guava-20.0.jar:na]
at com.google.common.collect.ImmutableList.copyOf(ImmutableList.java:209) ~[guava-20.0.jar:na]
at com.google.common.collect.FluentIterable.toList(FluentIterable.java:614) ~[guava-20.0.jar:na]
at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.defaultContextBuilder(DocumentationPluginsBootstrapper.java:111) ~[springfox-spring-web-2.9.2.jar:null]
at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.buildContext(DocumentationPluginsBootstrapper.java:96) ~[springfox-spring-web-2.9.2.jar:null]
at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:167) ~[springfox-spring-web-2.9.2.jar:null]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.13.jar:5.3.13]
... 19 common frames omitted
Searching about I tried to change versions to 2.8.0, 2.7.0, 3.0.0... also returns error.
The application is an apirest with task list activities.
try upgrade version of springfox, add spring fox starter and remove #EnableSwagger2
Dependencies to be added
<!--springfox dependencies for api documentations in swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
Remove anotations #EnableSwagger2
#Configuration
// #EnableSwagger2 // remove this annotation
public class SwaggerConfig { ... }
try on this link if there is no override changing in default path
http://localhost:{port}/swagger-ui/index.html
I have solved this issue in the Latest Spring Boot 2.6.7 version by following steps. Anyone can check who is facing this issue in 2.6.7 version.
Comment/Remove actuator dependency in pom.xml file
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-actuator</artifactId>-->
<!-- </dependency>-->
Add swagger dependency in pom.xml file
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
Swagger Configuration class change to
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
#Configuration
#EnableWebMvc
public class SwaggerConfig implements WebMvcConfigurer {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.companyname.app"))
.paths(PathSelectors.regex("/.*"))
.build().apiInfo(apiInfoMetaData());
}
private ApiInfo apiInfoMetaData() {
return new ApiInfoBuilder().title("NAME OF SERVICE")
.description("API Endpoint Decoration")
.contact(new Contact("Dev-Team", "https://www.dev-team.com/", "dev-team#gmail.com"))
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.version("1.0.0")
.build();
}
}
Swagger apis URL
My case
http://localhost:8080/swagger-ui/index.html
Your case if you different port and project context path
http://localhost:{port}/your-context-path/swagger-ui/index.html
The springfox plugin is not compatible with PathPattern-based matching in Spring MVC which has replaced the previous Ant-based matching in the Spring Boot default settings. See e.g. here
https://stackoverflow.com/a/70037507/15496965
https://stackoverflow.com/a/69814964/15496965
You can try to set spring.mvc.pathmatch.matching-strategy=ant_path_matcher to flip that property back to its previous default value. But this won't help if you use actuators which are not effected by that property.
You can try to force the actuators back to Ant-based matching as explained in the second post. But I'd really not recommend that. Instead, you can use Spring Boot <= 2.5 for the moment or migrate to springdoc.
I know this does not solve your problem directly, but consider moving to springdoc. Springfox is so buggy at this point that is a pain to use. I've moved to springdoc 2 years ago because of its Spring WebFlux support and I am very happy about it. Additionally, it also supports Kotlin Coroutines, which I am not sure Springfox does.
If you decide to migrate, springdoc even has a migration guide.
Additionally, you are already using Spring Boot 2.6, which is very very recent (its release notes are from a couple of hours ago) and thus springdoc and Springfox might not support it already. So I would also suggest you use Spring Boot 2.5.7 instead.
Just add this configuration to your application.properties
spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER
then Run your application.
You need to edit one part, the base package name. As shown in the screenshot my base package name.
my package name
#Configuration
#EnableSwagger2
public class SwaggerConfig2 {
#Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(true)
.apiInfo(new ApiInfoBuilder()
.title("Swagger Super")
.description("Swagger Description details")
.version("1.0").build())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.swagger.controller"))
.paths(PathSelectors.any()).build();
}
}
OR
#Configuration
#EnableSwagger2
public class SwaggerConfig2 {
#Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(true)
.apiInfo(new ApiInfoBuilder()
.title("Swagger Super")
.description("Swagger Description details")
.version("1.0").build())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any()).build();
}
}
And the Swagger Dependencies
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
<scope>compile</scope>
</dependency>
Try like this, I hope it will work
Note: SNAPSHOT, M1, M2, M3, and M4 releases typically WORK IN PROGRESS. The Spring team is still working on them, Recommend NOT using them.
It should be added, when i add it resolved
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
show the below all swagger dependency
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-schema</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
I had the same error, but I get down the org.springframework.boot to 2.5.8, and I had it on 2.7.1.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.8</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
And the Swagger Dependencies
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
And It works!!!
Add #Enablewebmvc in #Configuration class
and remove all other dependencies and include only below one for swagger
Add #Enablewebmvc in #Configuration class
and remove all other dependencies and include only below one for swagger
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency> "
Just adding below to your application.properties works like magic
spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER
I am trying to implement circuit breaker in my spring boot app.
I made 2 bare minimum microservices to test the implementation of circuit breaker.
Here is my code.
Microservice A:
application.properties
server.port=8076
resilience4j.circuitbreaker.instances.recordstore.sliding-window-size=4
resilience4j.circuitbreaker.instances.recordstore.minimum-number-of-calls=2
resilience4j.circuitbreaker.instances.recordstore.failure-rate-threshold=70
resilience4j.circuitbreaker.instances.recordstore.automatic-transition-from-open-to-half-open-enabled=true
#resilience4j.circuitbreaker.instances.recordstore.enable-exponential-backoff=true
resilience4j.circuitbreaker.instances.recordstore.permitted-number-of-calls-in-half-open-state=2
resilience4j.circuitbreaker.instances.recordstore.sliding-window-type=COUNT_BASED
resilience4j.circuitbreaker.instances.recordstore.wait-duration-in-open-state=10
resilience4j.circuitbreaker.instances.recordstore.writable-stack-trace-enabled=true
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>A</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>A</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot2</artifactId>
<version>1.7.1</version>
</dependency>
<!-- <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-timelimiter</artifactId>
<version>1.7.0</version> </dependency> -->
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-circuitbreaker</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
config
#Configuration
public class AConfig {
#Value("${resilience4j.circuitbreaker.instances.recordstore.minimum-number-of-calls}")
private int minimumNumberOfCalls;
#Value("${resilience4j.circuitbreaker.instances.recordstore.sliding-window-size}")
private int slidingWindowSize;
#Value("${resilience4j.circuitbreaker.instances.recordstore.sliding-window-type}")
private SlidingWindowType slidingWindowType;
#Value("${resilience4j.circuitbreaker.instances.recordstore.wait-duration-in-open-state}")
private int waitDurationInOpenState;
#Value("${resilience4j.circuitbreaker.instances.recordstore.failure-rate-threshold}")
private int failureRateThreshold;
#Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
#Bean
public CircuitBreaker circuitBreaker() {
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.slidingWindowSize(slidingWindowSize)
.slidingWindowType(slidingWindowType)
.waitDurationInOpenState(Duration.ofSeconds(waitDurationInOpenState))
.failureRateThreshold(failureRateThreshold)
.writableStackTraceEnabled(true)
.enableAutomaticTransitionFromOpenToHalfOpen()
.automaticTransitionFromOpenToHalfOpenEnabled(true)
.build();
CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.of(circuitBreakerConfig);
return circuitBreakerRegistry.circuitBreaker("recordstore", circuitBreakerConfig) ;
}
}
controller
#RestController
public class AController {
private static final Logger LOGGER = LoggerFactory.getLogger(AController.class);
#Autowired
RestTemplate restTemplate;
#Autowired
CircuitBreaker circuitBreaker;
#GetMapping("/test/{id}")
public void test(#PathVariable Integer id) {
System.out.println(" id :::" + id);
Supplier<String> supplier = () -> restTemplate.getForObject("http://localhost:8077/read", String.class);
Supplier<String> decoratedSupplier = circuitBreaker.decorateSupplier(supplier);
Try<String> response = Try.ofSupplier(decoratedSupplier).recover(throwable -> this.logId(id));
LOGGER.info("Response for id::: {} ...is.... {}" , id, response);
}
private String logId(Integer id) {
System.out.println("Logging id for RTB");
return "manual intervention needed";
}
}
Below is code of Microservice B:
#RestController
public class BController {
#GetMapping("/read")
public String read() {
System.out.println("in B");
return "Successsssssss";
}
}
Here are my logs. Initially microservice B is Up and I fire 3 request after that I bring microservice B down and fire another 6 requests.
2021-07-17 17:31:33.197 INFO 9904 --- [ main] com.example.demo.AApplication : Started AApplication in 3.808 seconds (JVM running for 4.722)
2021-07-17 17:31:53.562 INFO 9904 --- [nio-8076-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-07-17 17:31:53.562 INFO 9904 --- [nio-8076-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-07-17 17:31:53.564 INFO 9904 --- [nio-8076-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
id :::1
2021-07-17 17:31:53.948 INFO 9904 --- [nio-8076-exec-1] com.example.demo.AController : Response for id::: 1 ...is.... Success(Successsssssss)
id :::1
2021-07-17 17:31:57.466 INFO 9904 --- [nio-8076-exec-2] com.example.demo.AController : Response for id::: 1 ...is.... Success(Successsssssss)
id :::1
2021-07-17 17:32:11.553 INFO 9904 --- [nio-8076-exec-3] com.example.demo.AController : Response for id::: 1 ...is.... Success(Successsssssss)
id :::1
Logging id for RTB
2021-07-17 17:32:21.132 INFO 9904 --- [nio-8076-exec-4] com.example.demo.AController : Response for id::: 1 ...is.... Success(manual intervention needed)
id :::2
Logging id for RTB
2021-07-17 17:32:27.915 INFO 9904 --- [nio-8076-exec-5] com.example.demo.AController : Response for id::: 2 ...is.... Success(manual intervention needed)
id :::3
Logging id for RTB
2021-07-17 17:32:38.345 INFO 9904 --- [nio-8076-exec-6] com.example.demo.AController : Response for id::: 3 ...is.... Success(manual intervention needed)
id :::4
Logging id for RTB
2021-07-17 17:32:42.706 INFO 9904 --- [nio-8076-exec-7] com.example.demo.AController : Response for id::: 4 ...is.... Success(manual intervention needed)
id :::5
Logging id for RTB
2021-07-17 17:32:47.001 INFO 9904 --- [nio-8076-exec-8] com.example.demo.AController : Response for id::: 5 ...is.... Success(manual intervention needed)
id :::6
Logging id for RTB
2021-07-17 17:32:56.484 INFO 9904 --- [nio-8076-exec-9] com.example.demo.AController : Response for id::: 6 ...is.... Success(manual intervention needed)
I have invested 4 days now and am unable to understand why this simple thing is not working. Why does my circuit not open. I am feeling extreemly demotivated. Please someone who knows this help me. I will be really thankful to you.
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 am new to spring, and I have created a new spring boot project using https://start.spring.io/ with no further dependencies, unzipped the zip file and opened the project in IntelliJ IDEA. I have not done any further configurations. I am now trying to setup a bean with a #PostConstruct method - however, the method is never invoked by spring.
These are my classes:
SpringTestApplication.java
package com.habichty.test.testspring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
#SpringBootApplication
public class SpringTestApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(SpringTestApplication.class, args);
context.getBean(TestBean.class).testMethod();
}
}
TestBean.java
package com.habichty.test.testspring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
#Component
public class TestBean {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private int a = 1;
public TestBean()
{
log.debug("Constructor of TestBean called.");
}
#PostConstruct
public void init()
{
log.debug("init()-Method of TestBean called.");
a = 2;
}
public void testMethod()
{
log.debug("Test Method of TestBean called. a=" + a);
}
}
When I start the application, this is my output:
:: Spring Boot :: (v1.5.9.RELEASE)
2018-01-22 13:15:57.960 INFO 12035 --- [ main] c.h.t.testspring.SpringTestApplication : Starting SpringTestApplication on pbtp with PID 12035 (/home/pat/prj/testspring/testspring/target/classes started by pat in /home/pat/prj/testspring/testspring)
2018-01-22 13:15:57.962 DEBUG 12035 --- [ main] c.h.t.testspring.SpringTestApplication : Running with Spring Boot v1.5.9.RELEASE, Spring v4.3.13.RELEASE
2018-01-22 13:15:57.962 INFO 12035 --- [ main] c.h.t.testspring.SpringTestApplication : No active profile set, falling back to default profiles: default
2018-01-22 13:15:58.018 INFO 12035 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#2931522b: startup date [Mon Jan 22 13:15:58 CET 2018]; root of context hierarchy
2018-01-22 13:15:58.510 DEBUG 12035 --- [ main] com.habichty.test.testspring.TestBean : Constructor of TestBean called.
2018-01-22 13:15:58.793 INFO 12035 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-01-22 13:15:58.822 INFO 12035 --- [ main] c.h.t.testspring.SpringTestApplication : Started SpringTestApplication in 1.073 seconds (JVM running for 2.025)
2018-01-22 13:15:58.822 DEBUG 12035 --- [ main] com.habichty.test.testspring.TestBean : Test Method of TestBean called. a=1
2018-01-22 13:15:58.826 INFO 12035 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#2931522b: startup date [Mon Jan 22 13:15:58 CET 2018]; root of context hierarchy
2018-01-22 13:15:58.828 INFO 12035 --- [ Thread-1] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
As you can see, spring initializes the TestBean and also executes the testMethod() - but the init()-Method, annotated with #PostConstruct, is not invoked.
What am I doing wrong?
Any help is very appreciated.
UPDATE 1
In my application.properties, I have configured:
logging.level.com = DEBUG
Changing this to logging.level.root = DEBUG results in a massively bigger log. However, it still does not contain the debug message of my init() method.
UPDATE 2 Added package and import statements.
UPDATE 3 To further clarify that this is not a logging issue, I have added an new int to the code that should be altered by the init()-Method. As far as I understood the concept of the #PostConstruct annotation, it should be executed prior to any other method execution. As a consequence, the output of testMethod() should now contain a=2. In the updated output, you may see that this is not the case.
UPDATE 4 This 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.habichty.test.testspring</groupId>
<artifactId>springTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springTest</name>
<description>springTest</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</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The output of java -version:
java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)
Due to the new module system in Java9 SpringBoot-1.5.9 fails to process #PostConstruct as the annotation class is not on the classpath. The problem (or similar) is described here and here. There are a few ways to resolve it:
run the application with Java8, or, if still on Java9:
add javax.annotation:javax.annotation-api dependency to the POM, or
upgrade to a newer Spring-Boot of version 2.0.0+ (which is still PRERELEASE as of this writing) which incorporates that dependency;
I know this Problem is already solved, but as it is the first Stackoverflow Question that came up when I googled this problem I will leave this here:
I had the same issue and my error was that I had a typo in my package names. My class which was calling name had a different packagename than my SpringBootApplication class. So my main application was not finding my component.
So always check your package names if you have a similiar problems.
I guess you did not define something like
logging.level.root=debug
in your application.properties?
Without = no logs
With =
2018-01-22 12:34:06.117 DEBUG 8516 --- [main] com.example.demo.TestBean : Constructor of TestBean called.
...
2018-01-22 12:34:06.117 DEBUG 8516 --- [main] com.example.demo.TestBean : init()-Method of TestBean called.
...
2018-01-22 12:34:06.241 DEBUG 8516 --- [main] com.example.demo.TestBean : Test Method of TestBean called.
If you are using Java 9 or higher, then you will encounter an error when using #PostConstruct and #PreDestroy in your code.
Eclipse is unable to import #PostConstruct or #PreDestroy
When using Java 9 and higher, javax.annotation has been removed from its default classpath. That's why Eclipse can't find it.
Solution
Download the javax.annotation-api-1.3.2.jar from
https://search.maven.org/remotecontent?filepath=javax/annotation/javax.annotation-api/1.3.2/javax.annotation-api-1.3.2.jar
Copy the JAR file to the lib folder of your project
Use the following steps to add it to your Java Build Path.
Right-click your project, select Properties
On the left-hand side, click Java Build Path
In the top-center of dialog, click Libraries
Click Classpath and then Click Add JARs ...
Navigate to the JAR file /lib/javax.annotation-api-1.3.2.jar
Click OK then click Apply and Close
Eclipse will perform a rebuild of your project and it will resolve the related build errors.
I'm trying to do simple call to the method
BeanFactoryAnnotationUtils.qualifiedBeanOfType
Here the pom.xml of the project :
<?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>beanfactoryannotationutils.sample</groupId>
<artifactId>BeanFactoryAnnotationUtilsProblem</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- Spring boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
The Application.java class
#SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
ListableBeanFactory beanFactory = ctx.getBeanFactory();
// This is working ... (#Autowired with #Qualifier(...) too)
Map<String, QualifiedInterface> qualifiedBeans = beanFactory.getBeansOfType(QualifiedInterface.class);
System.out.println("Existing qualified beans ...");
for (QualifiedInterface qualifiedBean : qualifiedBeans.values()) {
System.out.println(" " + qualifiedBean.toString());
for (Annotation annotation : qualifiedBean.getClass().getAnnotations()) {
System.out.println(" - " + annotation.toString());
}
}
// This is working too ...
Map<String, Object> qualifiedBeansFromCtx = ctx.getBeansWithAnnotation(Qualifier.class);
System.out.println("Existing qualified beans from context ...");
for (Object qualifiedBean : qualifiedBeansFromCtx.values()) {
System.out.println(" " + qualifiedBean.toString());
for (Annotation annotation : qualifiedBean.getClass().getAnnotations()) {
System.out.println(" - " + annotation.toString());
}
}
// This is not ...
QualifiedInterface processor = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
beanFactory, QualifiedInterface.class, "QualifierA");
System.out.println("The selected processor should be A " + processor);
}
}
An interface QualifiedInterface.java
public interface QualifiedInterface {
}
Two beans QualifiedA.java
#Component
#Qualifier("QualifierA")
public class QualifiedA implements QualifiedInterface {
#Override
public String toString() {
return "QualifiedA";
}
}
and QualifiedB.java :
#Component
#Qualifier("QualifierB")
public class QualifiedB implements QualifiedInterface {
#Override
public String toString() {
return "QualifiedB";
}
}
The whole in the same package and application, now run it :
2015-12-24 15:08:34.468 INFO 9524 --- [ main] l.p.e.b.Application : Starting Application on DTBE-DEV4 with PID 9524 (D:\Workspace_netbeans\BeanFactoryAnnotationUtilsProblem\target\classes started by eguenichon in D:\Workspace_netbeans\BeanFactoryAnnotationUtilsProblem)
2015-12-24 15:08:34.478 INFO 9524 --- [ main] l.p.e.b.Application : No profiles are active
2015-12-24 15:08:34.618 INFO 9524 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#11e18e8c: startup date [Thu Dec 24 15:08:34 CET 2015]; root of context hierarchy
2015-12-24 15:08:37.516 INFO 9524 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2015-12-24 15:08:37.524 INFO 9524 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2015-12-24 15:08:37.672 INFO 9524 --- [ main] l.p.e.b.Application : Started Application in 3.715 seconds (JVM running for 4.355)
Existing qualified beans ...
QualifiedA
- #org.springframework.stereotype.Component(value=)
- #org.springframework.beans.factory.annotation.Qualifier(value=QualifierA)
QualifiedB
- #org.springframework.stereotype.Component(value=)
- #org.springframework.beans.factory.annotation.Qualifier(value=QualifierB)
Existing qualified beans from context ...
QualifiedA
- #org.springframework.stereotype.Component(value=)
- #org.springframework.beans.factory.annotation.Qualifier(value=QualifierA)
QualifiedB
- #org.springframework.stereotype.Component(value=)
- #org.springframework.beans.factory.annotation.Qualifier(value=QualifierB)
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'QualifierA' is defined: No matching QualifiedInterface bean found for qualifier 'QualifierA' - neither qualifier match nor bean name match!
at org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils.qualifiedBeanOfType(BeanFactoryAnnotationUtils.java:100)
at org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils.qualifiedBeanOfType(BeanFactoryAnnotationUtils.java:56)
at beanfactoryannotation.sample.beanfactoryannotationutilsproblem.Application.main(Application.java:45)
2015-12-24 15:08:37.684 INFO 9524 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#11e18e8c: startup date [Thu Dec 24 15:08:34 CET 2015]; root of context hierarchy
2015-12-24 15:08:37.686 INFO 9524 --- [ Thread-1] o.s.c.support.DefaultLifecycleProcessor : Stopping beans in phase 0
2015-12-24 15:08:37.691 INFO 9524 --- [ Thread-1] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
The BeanFactoryAnnotationUtils.qualifiedBeanOfType doesn't seems to works as the qualified beans exists in the context but could not be retrieved. Do you have an idea of what's the problem is here ?
Thanks !
This is not provided before Spring 4.3 due to the default specification of the BeanFactoryAnnotationUtils class.
See : https://jira.spring.io/browse/SPR-13819
While looking at the code behind the BeanFactoryAnnotationUtils.qualifiedBeanOfType(...) method, I noticed that the qualifier is checked from an AbstractBeanDefinition object. When I dump this object on our example I can notice that the "qualifiers" map is empty ?!?!?
It looks like a bug in the way Spring loads the bean definition with annotated qualifiers.
There is already an open issue that looks quite similar: https://jira.spring.io/browse/SPR-13452
I guess you could open another one specifically with your test case.