Spring Boot web application doesn't serve standard endpoints - java

I have a problem with a Spring Boot Application that is supposed to run from command line and at the same time serve some metrics from the standard /metrics endpoint. When I just created the application all the metrics were served correctly, but at some point I seem to have "broken" something and my application stopped serving from default endpoints. I can't just revert to the initial state because there's a lot of code already and I don't want to lose version control history. Maybe someone could point at what I am doing wrong?
I don't override dispatcher servlet and don't add any custom filters.
Spring Boot version 1.3.7.
Error when accessing /metrics or any other default endpoint:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing
this as a fallback.
Mon Oct 03 17:53:12 PDT 2016 There was an unexpected error (type=Not
Found, status=404). No message available
Application file:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Runner.class, args);
}
}
Main runner file:
#EnableConfigurationProperties(ApplicationProperties.class)
#SpringBootApplication
public class Runner implements CommandLineRunner {
#Override
public void run(String... strings) throws Exception {
// shortened ...
}
}
POM file fragment:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.7.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!-- spring boot -->
<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-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
Debug output shows that the filters are created:
2016-10-03 17:26:14.461 DEBUG 85880 --- [ost-startStop-1] o.s.b.c.e.ServletContextInitializerBeans : Added existing Servlet initializer bean 'dispatcherServletRegistration'; order=2147483647, resource=class path resource [org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfiguration$DispatcherServletConfiguration.class]
2016-10-03 17:26:14.720 DEBUG 85880 --- [ost-startStop-1] o.s.b.c.e.ServletContextInitializerBeans : Created Filter initializer for bean 'metricFilter'; order=-2147483648, resource=class path resource [org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfiguration.class]
I created a sample clean application to compare and there are lines in output that I don't have in my app:
2016-10-03 18:06:48.075 DEBUG 86858 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : 2 request handler methods found on class org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint: {public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)={[/{name:.*}],methods=[GET],produces=[application/json]}, public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()={[],methods=[GET],produces=[application/json]}}
2016-10-03 18:06:48.076 INFO 86858 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/metrics/{name:.*}],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2016-10-03 18:06:48.076 INFO 86858 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/metrics || /metrics.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
So, the filters/servlet seem to be created but not mapped in my app.
What am I possibly missing here?

OK I was stupid. Could say it twice.
So, after all, the problem was my bad memory. I actually was overriding application properties like this:
management.contextPath=/services/admin
Guess what, my /metrics was there all the time. It was just under /services/admin/metrics, which I completely forgot to have overridden. Duh.

Related

Spring Boot Controller not mapping (Whitelabel Error Page)

I have a Spring REST project that is redirecting all requests to error page, even if they are mapped in the controller.
I reduced the code to the smallest possible version that produces the error:
Here is the project structure:
Here is the Application class (The imports are removed to make the thread easier to read):
package com.example.demo;
#Controller
#SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#GetMapping("/greeting")
#ResponseBody
public String greeting() {
return "greeting";
}
}
Originally I hade a sperate controller from the App class, but moved the controller code to the app class to make sure that this is not a project structure problem
Here is the controller code (Tried with and without it, and received the same error):
#Controller
#SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#GetMapping("/hello")
#ResponseBody
public String greeting() {
return "greeting";
}
}
(Both http://localhost:8080/greeting as well as well http://localhost:8080/hello return the same error page)
Dependencies and plugins from the pom file:
<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-tomcat</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
(Tried with and without tomcat as dependency and nothing changed)
And lastly here is the error message I receive in the browser when I visit the links (http://localhost:8080/greeting and http://localhost:8080/hello):
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Nov 27 00:16:08 CET 2022
There was an unexpected error (type=Not Found, status=404).
Edit:
After setting debug to true in project.properties, here is the error message I see in console (Worth mentioning that the project ran with no issues when I tried it on another system (Same OS)):
GET "/greeting", parameters={}
Mapped to ResourceHttpRequestHandler [classpath [META-INF/resources/], classpath [resources/], classpath [static/], classpath [public/], ServletContext [/]]
Resource not found
Completed 404 NOT_FOUND
"ERROR" dispatch for GET "/error", parameters={}
(Timestamps are removed to make reading easier)
Did you tried making call to the endpoint via postman ? If so, can you try again after removing #ResponseBody annotation.
Instead of #Controller use #RestController

Spring boot web app not running on tomcat 9

My web App works fine on Eclipse Photon STS, java 8 and Spring Boot 2.02 with the embeded tomcat using endpoint:
http://localhost:8081/DataViewer/tspsPatentSearch
But when I compile the code into DataViewer.war file (using mvn package) and run it on Tomcat 9 on Linux
with endpoint:
http://myserver.com:8081/DataViewer/tspsPatentSearch
I get the infamous:
Whitelabel Error Page
There was an unexpected error (type=Not Found, status=404).
/DataViewer/tspsPatentSearch
My pom.xml file is:
`<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion>
<groupId>com.clarivate</groupId>
<artifactId>dataviewer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>dataviewer</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.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>
<start-class>com.clarivate.dataviewer.DvMain</start-class>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- DS may need to remove for tomcat installation -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<!-- Required to find ojdbc6, because Oracle don't make it available to maven-->
<repositories>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<build>
<finalName>DataViewer</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.clarivate.dataviewer.DvMain</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<description>TSPS data viewer</description>
In application.properties I have:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
server.servlet.path=/DataViewer
My main class is:
package com.clarivate.dataviewer;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication
public class DvMain extends SpringBootServletInitializer {
static Logger logger = LogManager.getRootLogger();
public static void main(String[] args) {
logger.debug("DS1A in main()");
SpringApplication.run(DvMain.class, args);
logger.info("DS1C finished.");
}
//#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(DvMain.class);
}
}
My MainController.java has:
#GetMapping("/tspsPatentSearch")
public String tspsPatentSearch(Model model) {
model.addAttribute("tspsPatent", new TspsPatent());
return "tspsPatentSearch";
}
The war file unpacks fine and there are no errors. In catalina.out we have:
2018-10-04 12:09:09.954 INFO 12950 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/tspsPatentSearch],methods=[POST]}" onto public java.lang.String com.clarivate.dataviewer.controller.MainController.tspsPatentSearch(com.clarivate.dataviewer.model.TspsPatent,org.springframework.ui.Model,org.springframework.validation.BindingResult)
and no errors. I've tried this ie my package structure is correct and this ie my jsp's are in the correct location (data_viewer\src\main\webapp\WEB-INF\jsp)
and i'm now running short of ideas. Any help much appreciated
Edit: If I copy tspsPatentSearch.jsp into the war file top directory then tomcat finds it. So it looks like tomcat is ignoring:
spring.mvc.view.prefix=/WEB-INF/jsp/
or not finding application.properties at all.
Add this to your application.properties:
server.servlet.contextPath=/
I've taken your sample code and, assuming you annotated your MainController simply as #Controller, put a deployment together. I changed a few things around, but I believe this was the bit that did it. I haven't been able to find any references explaining why it might be required by Tomcat, but I intend to keep looking. I'll update you if I find anything.
Edit:
I noticed some duplicate logging in Spring 2.0.2 related to this issue: https://github.com/spring-projects/spring-boot/issues/13470
The problem appeared fixed in 2.0.4 therefore I upgraded.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
Additionally, I removed the server.servlet.contextPath=/ entry and tada I still can reach the Hello World jsp I set up. If upgrading is possible for you, maybe you could try that before adding something to application.properties which could be considered duplicated functionality. At least I can promise you a better logging experience.
Edit #2:
No smoking gun, so far, but these (from 2.0.4) could be related:
Provide a consistent way to discover the primary DispatcherServlet's path
Dispatcher servlets with a custom servlet name are not found by the mappings endpoint
Nothing looked likely on a surface scan of 2.0.3. I'm going to give it a rest for now and give you a chance to try some stuff. Good luck!
Edit #3:
I'm sorry to continue suggesting you switch environment stuff around, but one difference I noted between what I tested and what you're working with is that you seem to be using Tomcat-9.0.0.M20 where as I was testing with 9.0.12.
Whether you want to upgrade or not, a few things to note and/or do:
1) Update your question with what you've got now if it's different than before. Include the server.servlet.contextPath=/ in your application.properties just so anyone else looking can see what you've done.
2) The exclusion you have for spring-boot-starter-tomcat under spring-boot-starter-web doesn't appear to do anything - you can verify by comparing the output from running mvn dependency:tree before and after removal.
3) I'm not sure that your spring-web dependency is needed either, as that's brought in by default under the spring-boot-starter.
4) Now to your output. Spring Boot is coming up (note the banner) and your classes are being found and acted upon.
catalina.out.DEBUG also in your DS.log starting ~ 08:35:38.162
2018-10-12 09:30:17.322 DEBUG 55745 --- [ main] o.s.c.a.ClassPathBeanDefinitionScanner : Identified candidate component class: file [/data/apps/tomcat/apache-tomcat-9.0.0.M20/webapps/DataViewer/WEB-INF/classes/com/clarivate/dataviewer/controller/MainController.class]
2018-10-12 09:30:17.328 DEBUG 55745 --- [ main] o.s.c.a.ClassPathBeanDefinitionScanner : Identified candidate component class: file [/data/apps/tomcat/apache-tomcat-9.0.0.M20/webapps/DataViewer/WEB-INF/classes/com/clarivate/dataviewer/database/ReadFromDb.class]
2018-10-12 09:30:17.356 DEBUG 55745 --- [ main] o.s.c.a.ClassPathBeanDefinitionScanner : Identified candidate component class: file [/data/apps/tomcat/apache-tomcat-9.0.0.M20/webapps/DataViewer/WEB-INF/classes/com/clarivate/dataviewer/service/FileFuncs.class]
2018-10-12 09:30:17.357 DEBUG 55745 --- [ main] o.s.c.a.ClassPathBeanDefinitionScanner : Identified candidate component class: file [/data/apps/tomcat/apache-tomcat-9.0.0.M20/webapps/DataViewer/WEB-INF/classes/com/clarivate/dataviewer/service/StringFuncs.class]
...
2018-10-12 09:30:19.417 INFO 55745 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/tspsPatentSearch],methods=[POST]}" onto public java.lang.String com.clarivate.dataviewer.controller.MainController.tspsPatentSearch(com.clarivate.dataviewer.model.TspsPatent,org.springframework.ui.Model,org.springframework.validation.BindingResult)
2018-10-12 09:30:19.417 INFO 55745 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/tspsPatentSearch],methods=[GET]}" onto public java.lang.String com.clarivate.dataviewer.controller.MainController.tspsPatentSearch(org.springframework.ui.Model)
...
2018-10-12 09:30:19.769 INFO 55745 --- [ main] com.clarivate.dataviewer.DvMain : Started DvMain in 3.125 seconds (JVM running for 5.845)
And I do indeed note the mapping to /error that's returned for your request at 09:32:11.
I find this strange:
2018-10-12 09:32:11.758 DEBUG 55745 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/DataViewer/DataViewer/error]
And it's different in DS.log:
2018-10-12 08:36:56.136 DEBUG 6992 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/DataViewer /error]
Specifically /DataViewer/DataViewer/error - have you tried requesting http://localhost:8081/DataViewer/DataViewer/tspsPatentSearch
In general this appears as though everything is coming up but there is a misconfiguration somewhere that isn't allowing a request to map to the handler.
To confirm.
Tomcat adds the war file name to the end point, so if we create DataViewerX.war and set :
server.servlet.path=/DataViewer
then the end point when running on an external tomcat is:
myServer.com/DataViewerX/DataViewer/tspsPatentSearch
but when we run on Eclispe, using the source code, then the end point is:
http://localhost:8081/DataViewer/tspsPatentSearch
which is a bit annoying but not a major problem. A way round this is to call the war file ROOT.war, then tomcat ignores the war file name and the 2 end points are the same, but I have multiple war files in the webapps dir so this solution isn't acceptable for me.
If anyone know's a way to allow the 2 end points to be the same then please say so, but it's not that important.

spring boot - #PostConstruct not called on #Component

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.

Spring cloud config cannot load native config file unless the filename is application

Something strange happened to me. I have no idea about how to solve it that the spring cloud config cannot load native or cloud config file unless it's filename is 'application.yml/application.properties'.
The below code is my configuration:
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>micro-certification-config-center</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
ConfigServer:
#SpringBootApplication
#EnableConfigServer
public class ConfigServer {
public static void main(String[] args) {
SpringApplication.run(ConfigServer.class, args);
}
}
application.yml:
server:
port: 8000
spring:
cloud:
config:
server:
native:
search-locations: classpath:/shared
profiles:
active: native
The shared folder structor:
resources
-- shared
-- -- application-dev.yml
-- -- sms-dev.yml
It looks good and run well with no errors, but when I visit http://127.0.0.1:8000/configCenter/dev/master, it only shows the application property source.
The response:
{
"name": "configCenter",
"profiles": [
"dev"
],
"label": "master",
"version": null,
"state": null,
"propertySources": [
{
"name": "classpath:/shared/application-dev.yml",
"source": {
"logging.level.org.springframework.security": "INFO",
"eureka.instance.prefer-ip-address": true,
"eureka.client.serviceUrl.defaultZone": "http://registry:8761/eureka/",
"security.oauth2.resource.user-info-uri": "http://auth-service:5000/uaa/users/current",
"spring.rabbitmq.host": "rabbitmq"
}
}
]
}
The server console:
2017-08-24 22:34:08.055 INFO 30010 --- [nio-8000-exec-4] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#4a931797: startup date [Thu Aug 24 22:34:08 CST 2017]; root of context hierarchy
2017-08-24 22:34:08.062 INFO 30010 --- [nio-8000-exec-4] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-08-24 22:34:08.075 INFO 30010 --- [nio-8000-exec-4] o.s.c.c.s.e.NativeEnvironmentRepository : Adding property source: classpath:/shared/application-dev.yml
2017-08-24 22:34:08.075 INFO 30010 --- [nio-8000-exec-4] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#4a931797: startup date [Thu Aug 24 22:34:08 CST 2017]; root of context hierarchy
All above shows the 'application.yml' file only worked.
Can someone help me? Thanks very much!
The external config can help you that. The detail is here: http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
You can change this default application config to the external one by command like in the guide line:
If you don’t like application.properties as the configuration file
name you can switch to another by specifying a spring.config.name
environment property. You can also refer to an explicit location using
the spring.config.location environment property (comma-separated list
of directory locations, or file paths).
$ java -jar myproject.jar --spring.config.name=myproject or
$ java -jar myproject.jar
--spring.config.location=classpath:/default.properties,classpath:/override.properties
Or in your code you can put it like:
new SpringApplicationBuilder(Application.class)
.properties("spring.config.name:YOUR_EXTERNAL_CONFIG_FILE")
.build()
.run(args);
}
Hope this help.
As #spencergibb said, if I want to load sms-dev.yml, I should rename application.name to sms.

Spring Boot MVC : URL not published but shown in the boot logs

I'm just starting a very simple Spring MVC with Spring Boot (and Groovy), and I can't get my controller to be routed correctly, for example :
package net.kedare
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
#SpringBootApplication
class SpringLedControllerApplication {
static void main(String[] args) {
SpringApplication.run SpringLedControllerApplication, args
}
}
#Controller
#RequestMapping("/")
class SpringLedController {
#RequestMapping(method=RequestMethod.GET)
public String index() {
return "Hello"
}
}
It appears in the boot logs :
2016-01-23 14:09:28.588 INFO 57995 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String net.kedare.SpringLedController.index()
But when I go to the URL : "http://localhost:8080/", I get this :
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Jan 23 14:09:58 CET 2016
There was an unexpected error (type=Not Found, status=404).
No message available
Looks like it redirects to /error, but I don't know why..
Add this dependency in your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Categories

Resources