When using my Eclipse's Tomcat9 server (v9.0.62), my "application" runs normally.
Once deployed on my production server however (v9.0.43), 404 is returned.
No stacktraces are being logged by Tomcat.
Both servers use OpenJDK17 as JDK.
This problem does not happen when using versions of Spring < 6.
Eclipse console output:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.1)
2023-01-05T11:07:33.198+01:00 INFO 28395 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication using Java 17.0.5 with PID 28395 (/home/-----/demo/target/classes started by ----- in /home/-----/demo)
2023-01-05T11:07:33.207+01:00 INFO 28395 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default"
2023-01-05T11:07:34.391+01:00 INFO 28395 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2023-01-05T11:07:34.403+01:00 INFO 28395 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-01-05T11:07:34.404+01:00 INFO 28395 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.4]
2023-01-05T11:07:34.530+01:00 INFO 28395 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2023-01-05T11:07:34.532+01:00 INFO 28395 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1263 ms
2023-01-05T11:07:34.889+01:00 INFO 28395 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2023-01-05T11:07:34.895+01:00 INFO 28395 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 2.316 seconds (process running for 2.652)
2023-01-05T11:07:47.016+01:00 INFO 28395 --- [nio-8081-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-01-05T11:07:47.016+01:00 INFO 28395 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2023-01-05T11:07:47.017+01:00 INFO 28395 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
When building (maven clean install) the war file, still no issue:
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------------< com.example:demo >--------------------------
[INFO] Building demo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.2.0:clean (default-clean) # demo ---
[INFO] Deleting /home/-----/demo/target
[INFO]
[INFO] --- maven-resources-plugin:3.3.0:resources (default-resources) # demo ---
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.10.1:compile (default-compile) # demo ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to /home/-----/demo/target/classes
[INFO]
[INFO] --- maven-resources-plugin:3.3.0:testResources (default-testResources) # demo ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.10.1:testCompile (default-testCompile) # demo ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) # demo ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-war-plugin:3.3.2:war (default-war) # demo ---
[INFO] Packaging webapp
[INFO] Assembling webapp [demo] in [/home/-----/demo/target/demo-0.0.1-SNAPSHOT]
[INFO] Processing war project
[INFO] Copying webapp resources [/home/-----/demo/src/main/webapp]
[INFO] Building war: /home/-----/demo/target/demo-0.0.1-SNAPSHOT.war
[INFO]
[INFO] --- spring-boot-maven-plugin:3.0.1:repackage (repackage) # demo ---
[INFO] Replacing main artifact with repackaged archive
[INFO]
[INFO] --- maven-install-plugin:3.0.1:install (default-install) # demo ---
[INFO] Installing /home/-----/demo/pom.xml to /home/--/.m2/repository/com/example/demo/0.0.1-SNAPSHOT/demo-0.0.1-SNAPSHOT.pom
[INFO] Installing /home/-----/demo/target/demo-0.0.1-SNAPSHOT.war to /home/--/.m2/repository/com/example/demo/0.0.1-SNAPSHOT/demo-0.0.1-SNAPSHOT.war
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.232 s
[INFO] Finished at: 2023-01-05T11:09:35+01:00
[INFO] ------------------------------------------------------------------------
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>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
<!-- <tomcat.version>9.0.62</tomcat.version>-->
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
ServletInitializer:
package com.example.demo;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DemoApplication.class);
}
}
Controller:
package com.example.demo.ctrl;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class MainController {
#GetMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE)
public #ResponseBody String getMain() {
return "super";
}
}
Expected (Eclipse's server):
Found (Production server):
To pinpoint the problem (as my project is rather large), I reproduced the issue with a simple app based on Spring Initializr.
I attempted tweaking the pom.xml to no avail.
Spring boot 3 requires at least JDK17 and Tomcat 10 due to the package renaming from javax to jakarta.
Tomcat 9 does not work with jakarta packages which were changes introduced in Spring 6/Spring boot 3.
If you want to stay on Tomcat 9 you will need to downgrade to Spring boot version 2.x.x, any Spring boot 3 version will require Tomcat upgrade to version 10.
Related
I have just installed today java spring but I came along a lot of problem normally when I start default spring version comes with 2.3.2(old version) I want to set up as 2.7.0.(upgraded)
I arranged upper edition,error sign comes always.Pom.xml file stand like OK but I do not know wheather fine.
I installed org.codehaus... maven file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>baris</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
maven output:
cd C:\Users\pc\Documents\NetBeansProjects\initbaris; "JAVA_HOME=C:\\Program Files\\Java\\jdk-17.0.1" cmd /c "\"C:\\Program Files\\NetBeans-12.6\\netbeans\\java\\maven\\bin\\mvn.cmd\" -Dexec.vmArgs= \"-Dexec.args=${exec.vmArgs} -classpath %classpath ${exec.mainClass} ${exec.appArgs}\" \"-Dexec.executable=C:\\Program Files\\Java\\jdk-17.0.1\\bin\\java.exe\" -Dexec.mainClass=baris.demo.DemoApplication -Dexec.classpathScope=runtime -DskipTests=true -Dexec.appArgs= \"-Dmaven.ext.class.path=C:\\Program Files\\NetBeans-12.6\\netbeans\\java\\maven-nblib\\netbeans-eventspy.jar\" -Dfile.encoding=UTF-8 org.codehaus.mojo:exec-maven-plugin:3.0.0:exec"
Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------------------< baris:demo >-----------------------------
[INFO] Building demo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- exec-maven-plugin:3.0.0:exec (default-cli) # demo ---
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.0)
2022-06-19 03:45:20.730 INFO 18280 --- [ main] baris.demo.DemoApplication : Starting DemoApplication using Java 17.0.1 on bz with PID 18280 (C:\Users\pc\Documents\NetBeansProjects\initbaris\target\classes started by pc in C:\Users\pc\Documents\NetBeansProjects\initbaris)
2022-06-19 03:45:20.734 INFO 18280 --- [ main] baris.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default"
2022-06-19 03:45:21.842 INFO 18280 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-06-19 03:45:21.867 INFO 18280 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 8 ms. Found 0 JPA repository interfaces.
2022-06-19 03:45:22.972 INFO 18280 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-06-19 03:45:22.988 INFO 18280 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-06-19 03:45:22.989 INFO 18280 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.63]
2022-06-19 03:45:23.199 INFO 18280 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-06-19 03:45:23.200 INFO 18280 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2400 ms
2022-06-19 03:45:23.288 WARN 18280 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Unsatisfied dependency expressed through method 'dataSourceScriptDatabaseInitializer' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
2022-06-19 03:45:23.294 INFO 18280 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-06-19 03:45:23.315 INFO 18280 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-06-19 03:45:23.348 ERROR 18280 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
[ERROR] Command execution failed.
org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
at org.apache.commons.exec.DefaultExecutor.executeInternal (DefaultExecutor.java:404)
at org.apache.commons.exec.DefaultExecutor.execute (DefaultExecutor.java:166)
at org.codehaus.mojo.exec.ExecMojo.executeCommandLine (ExecMojo.java:982)
at org.codehaus.mojo.exec.ExecMojo.executeCommandLine (ExecMojo.java:929)
at org.codehaus.mojo.exec.ExecMojo.execute (ExecMojo.java:457)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:568)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.250 s
[INFO] Finished at: 2022-06-19T03:45:24+03:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.0.0:exec (default-cli) on project demo: Command execution failed.: Process exited with an error: 1 (Exit value: 1) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
The error you are getting because of the postgresql.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
Comment these line and try to run the code.
I try to run spring boot application in Docker, Circle CI. Please, check how my .circleci/config.yml file looks like:
version: 2.1
jobs:
test:
docker:
- image: maven:3.8.5-openjdk-17-slim
environment:
CHROMEDRIVER_VERSION: 100.0.4896.60
CHROMEDRIVER_DIR: /tmp/chromedriver/
WIKI_ENV: CIRCLE_CI
steps:
- checkout
- run:
name: "Install gnupg2, wget, xvfb and unzip"
command: |
apt-get update
apt-get install -y gnupg2
apt-get install -y wget xvfb unzip
- run:
name: "Install Chrome Browser"
command: |
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list
apt-get update -y
apt-get install -y google-chrome-stable
- run:
name: "Setup chromedriver"
command: |
mkdir -p $CHROMEDRIVER_DIR
wget -q --continue -P $CHROMEDRIVER_DIR "http://chromedriver.storage.googleapis.com/$CHROMEDRIVER_VERSION/chromedriver_linux64.zip"
unzip $CHROMEDRIVER_DIR/chromedriver* -d $CHROMEDRIVER_DIR
export PATH=$CHROMEDRIVER_DIR:$PATH
- run:
name: "Build jar"
command: mvn clean package spring-boot:repackage
- run:
name: "Start"
command: mvn spring-boot:start
- run:
name: "Check"
command: curl http://localhost:8080
- store_test_results:
path: target/surefire-reports/junitreports
- store_artifacts:
path: target/surefire-reports/junitreports
- store_artifacts:
path: target/screenshots
workflows:
default:
jobs:
- test
A pipeline fails on a "Check" step with the curl: (7) Failed to connect to localhost port 8080: Connection refused error.
Here is the output of the "Start" step:
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for vznd:selenium:jar:1.0
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.testng:testng:jar -> duplicate declaration of version ${testng.version} # line 54, column 21
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ---------------------------< vznd:selenium >----------------------------
[INFO] Building selenium 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- spring-boot-maven-plugin:2.6.3:start (default-cli) # selenium ---
[INFO] Attaching agents: []
18:36:09.878 [Thread-0] DEBUG org.springframework.boot.devtools.restart.classloader.RestartClassLoader - Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader#2c5fa29b
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.3)
2022-05-05 18:36:10.165 INFO 4520 --- [ restartedMain] vznd.selenium.SeleniumApp : Starting SeleniumApp using Java 17.0.2 on aeadb1d9da7e with PID 4520 (/root/project/target/classes started by root in /root/project)
2022-05-05 18:36:10.166 INFO 4520 --- [ restartedMain] vznd.selenium.SeleniumApp : No active profile set, falling back to default profiles: default
2022-05-05 18:36:10.239 INFO 4520 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-05-05 18:36:10.239 INFO 4520 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-05-05 18:36:11.021 INFO 4520 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-05-05 18:36:11.034 INFO 4520 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-05-05 18:36:11.035 INFO 4520 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-05-05 18:36:11.086 INFO 4520 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-05-05 18:36:11.086 INFO 4520 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 846 ms
2022-05-05 18:36:11.320 INFO 4520 --- [ restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]
2022-05-05 18:36:11.418 INFO 4520 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2022-05-05 18:36:11.459 INFO 4520 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-05-05 18:36:11.468 INFO 4520 --- [ restartedMain] vznd.selenium.SeleniumApp : Started SeleniumApp in 1.58 seconds (JVM running for 2.136)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.129 s
[INFO] Finished at: 2022-05-05T18:36:11Z
[INFO] ------------------------------------------------------------------------
Here is my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>vznd</groupId>
<artifactId>selenium</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<maven-surefire-plugin.version>3.0.0-M6</maven-surefire-plugin.version>
<testng.version>7.5</testng.version>
<selenium-java.version>3.141.59</selenium-java.version>
<commons-io.version>2.11.0</commons-io.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium-java.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<systemPropertyVariables>
<webdriver.chrome.driver>/tmp/chromedriver/chromedriver</webdriver.chrome.driver>
</systemPropertyVariables>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</project>
When I run this commands locally - it works. When it executes on CI - it fails. What I tried to fix:
Run java -jar target/selenium.jar & command on the "Start" step
Run mvn spring-boot:run & command instead of "Build jar" and "Start" steps
Run nohup mvn spring-boot:run & command instead of "Build jar" and "Start" steps
Add sleep 120 step after the "Start" step
Could you please advise me what I am doing wrong?
Pretty sure you are curl'ing before server even started, so try to wait for server to start with
- run:
name: wait
command: sleep 10
Moved to a gitlab CI, the problem is not actual anymore.
So, I created an external configuration file named mystoreroom.yml in "/home/ivan/.config/spring-projects" directory, and I tried specifying its location when launching using the following command:
ivan#IVAN-LAPTOP:~/Projects/Java/my-storeroom$ mvn spring-boot:run -D spring-boot.run.arguments=--spring.config.location=/home/ivan/.config/spring-projects/mystoreroom.yml
After doing that I got an error:
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building my-storeroom 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> spring-boot-maven-plugin:2.3.5.RELEASE:run (default-cli) > test-compile # my-storeroom >>>
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) # my-storeroom ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) # my-storeroom ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) # my-storeroom ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/ivan/Projects/Java/my-storeroom/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) # my-storeroom ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] <<< spring-boot-maven-plugin:2.3.5.RELEASE:run (default-cli) < test-compile # my-storeroom <<<
[INFO]
[INFO] --- spring-boot-maven-plugin:2.3.5.RELEASE:run (default-cli) # my-storeroom ---
[INFO] Attaching agents: []
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.5.RELEASE)
2020-11-04 00:20:55.577 INFO 31741 --- [ main] c.r.mystoreroom.MyStoreroomApplication : Starting MyStoreroomApplication on IVAN-LAPTOP with PID 31741 (/home/ivan/Projects/Java/my-storeroom/target/classes started by ivan in /home/ivan/Projects/Java/my-storeroom)
2020-11-04 00:20:55.580 INFO 31741 --- [ main] c.r.mystoreroom.MyStoreroomApplication : No active profile set, falling back to default profiles: default
2020-11-04 00:20:56.418 INFO 31741 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-11-04 00:20:56.427 INFO 31741 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-11-04 00:20:56.427 INFO 31741 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.39]
2020-11-04 00:20:56.478 INFO 31741 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-11-04 00:20:56.478 INFO 31741 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 847 ms
2020-11-04 00:20:56.525 WARN 31741 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'foo' in value "${foo}"
2020-11-04 00:20:56.528 INFO 31741 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-11-04 00:20:56.541 INFO 31741 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-11-04 00:20:56.551 ERROR 31741 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'foo' in value "${foo}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1420) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:405) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
at com.repeta.mystoreroom.MyStoreroomApplication.main(MyStoreroomApplication.java:10) [classes/:na]
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'foo' in value "${foo}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178) ~[spring-core-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124) ~[spring-core-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:918) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
... 18 common frames omitted
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.586 s
[INFO] Finished at: 2020-11-04T00:20:56+02:00
[INFO] Final Memory: 20M/212M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.3.5.RELEASE:run (default-cli) on project my-storeroom: Application finished with exit code: 1 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
Then I moved mystoreroom.yml to "/home/ivan" directory and tried again:
ivan#IVAN-LAPTOP:~/Projects/Java/my-storeroom$ mvn spring-boot:run -D spring-boot.run.arguments=--spring.config.location=/home/ivan/mystoreroom.yml
This time everything was fine and /foo endpoint successfully printed "bar"
Am I doing something wrong? Or is it suppose to work like that?
Here's the code that I'm using:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.repeta</groupId>
<artifactId>my-storeroom</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>my-storeroom</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-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
mystoreroom.yml
spring:
security:
oauth2:
client:
registration:
github:
clientId: <hidden>
clientSecret: <hidden>
foo: bar
UserController.java
package com.repeta.mystoreroom;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class UserController {
#Value("${foo}")
private String foo;
#GetMapping("/foo")
public String foo(){
return foo;
}
}
I think I stumbled across the same problem. In Spring Boot 2.3.4 the "." in the path was not a problem yet. Since 2.3.5 is released, configurations under "hidden" folders are no longer found. In my case these are not external, rather configurations in the classpath as they are found unpackaged while building. In my mixed maven build environment I have "target" and ".target". The last one is causing problems since 2.3.5. Based on your description, I suspect that this is a new bug.
Bug / Issue 23983
Hi,
I'm trying to create a Java Spring web application for university classes. I created the Rest controller class connected to two service classes. The services classes are connected to the database via JPA. When I got rid of the errors related to the build problem, I decided to check if everything is correctly visible in swagger. And here the problem arises because despite creating the configuration file the server does not start. The application compiles correctly but the tomcat server does not appear and it is not possible to connect to the server via localhost: 8080. If there were any error, I would manage, but in the console everything looks fine, or I just think so.
Rest Controller class:
#RestController
public class JDBCController {
#Autowired
private IDelegationService delegationService;
#Autowired
private IUserService userService;
#RequestMapping(value = "/registerUser", method = RequestMethod.POST)
#ResponseBody
public void registerUser(#ModelAttribute User user) {
userService.save(user);
}
#RequestMapping(value = "/getAllUsers", method = RequestMethod.GET)
#ResponseBody
public List<User> getAllUsers() {
return userService.findAll();
}
#RequestMapping(value = "/changePassword", method = RequestMethod.PUT)
#ResponseBody
public void changePassword(#RequestParam("userId") long userId, #RequestParam("newPassword") String newPassword) {
userService.updatePassword(userId, newPassword);
}
#RequestMapping(value = "/deleteUserById", method = RequestMethod.DELETE)
#ResponseBody
public boolean deleteUserById(#RequestParam("userId") long userId) {
return userService.deleteById(userId);
}
#RequestMapping(value = "/getAllUsersByRoleName", method = RequestMethod.GET)
#ResponseBody
public List<User> getAllUsersByRoleName(#RequestParam("roleName") String roleName) {
return userService.getAllUsersByRoleName(roleName);
}
#RequestMapping(value = "/addDelegation", method = RequestMethod.POST)
#ResponseBody
public void addDelegation(#RequestParam("userId") long userId, #ModelAttribute Delegation delegation) {
delegationService.save(userId, delegation);
}
#RequestMapping(value = "/removeDelegation", method = RequestMethod.DELETE)
#ResponseBody
public boolean removeDelegation(#RequestParam("userId") long userId,
#RequestParam("delegationId") long delegationId) {
if (delegationId != 0L) {
return delegationService.deleteById(delegationId);
} else if (userId != 0L) {
return delegationService.deleteByUser(userId);
}
return false;
}
#RequestMapping(value = "/changeDelegation", method = RequestMethod.PUT)
#ResponseBody
public void changeDelegation(#RequestParam("delegationId") long delegationId,
#ModelAttribute Delegation delegation) {
delegationService.updateDelegation(delegationId, delegation);
}
#RequestMapping(value = "/getAllDelegations", method = RequestMethod.GET)
#ResponseBody
public List<Delegation> getAllDelegations(){
return delegationService.findAll();
}
#RequestMapping(value = "/getAllDelegationsOrderByDateStartDesc", method = RequestMethod.GET)
#ResponseBody
public List<Delegation> getAllDelegationsOrderByDateStartDesc(){
return delegationService.findAllOrderByDateStartDesc();
}
#RequestMapping(value = "/getAllDelegationsByUserOrderByDateStartDesc", method = RequestMethod.GET)
#ResponseBody
public List<Delegation> getAllDelegationsByUserOrderByDateStartDesc(#RequestParam("userId") Long userId){
return delegationService.findByUserOrderByDateStartDesc(userId);
}
}
Swagger config class:
#Configuration
#EnableSwagger2
public class SpringFoxConfig {
#Bean
public Docket mainConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/swagger")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class);
}
}
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.2.5.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.project</groupId>
<artifactId>Laboratorium1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Laboratorium1</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</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>
Console:
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< com.project:Laboratorium1 >----------------------
[INFO] Building Laboratorium1 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] >>> spring-boot-maven-plugin:2.2.5.RELEASE:run (default-cli) > test-compile # Laboratorium1 >>>
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) # Laboratorium1 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) # Laboratorium1 ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) # Laboratorium1 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\Admin\eclipse-workspace\PSS_Kulesza_Durol\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) # Laboratorium1 ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] <<< spring-boot-maven-plugin:2.2.5.RELEASE:run (default-cli) < test-compile # Laboratorium1 <<<
[INFO]
[INFO]
[INFO] --- spring-boot-maven-plugin:2.2.5.RELEASE:run (default-cli) # Laboratorium1 ---
[INFO] Attaching agents: []
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.5.RELEASE)
2020-03-16 20:18:07.785 INFO 4176 --- [ main] c.p.L.Laboratorium1Application : Starting Laboratorium1Application on DESKTOP-7SPKPTP with PID 4176 (C:\Users\Admin\eclipse-workspace\PSS_Kulesza_Durol\target\classes started by Admin in C:\Users\Admin\eclipse-workspace\PSS_Kulesza_Durol)
2020-03-16 20:18:07.788 INFO 4176 --- [ main] c.p.L.Laboratorium1Application : No active profile set, falling back to default profiles: default
2020-03-16 20:18:08.357 INFO 4176 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-03-16 20:18:08.456 INFO 4176 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 90ms. Found 3 JPA repository interfaces.
2020-03-16 20:18:08.898 INFO 4176 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-03-16 20:18:09.040 INFO 4176 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-03-16 20:18:09.187 INFO 4176 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-03-16 20:18:09.521 INFO 4176 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-03-16 20:18:10.116 INFO 4176 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-03-16 20:18:10.137 INFO 4176 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2020-03-16 20:18:11.044 INFO 4176 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-03-16 20:18:11.051 INFO 4176 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-03-16 20:18:11.720 INFO 4176 --- [ main] c.p.L.Laboratorium1Application : Started Laboratorium1Application in 4.355 seconds (JVM running for 4.983)
2020-03-16 20:18:11.726 INFO 4176 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-03-16 20:18:11.729 INFO 4176 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-03-16 20:18:11.734 INFO 4176 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.320 s
[INFO] Finished at: 2020-03-16T20:18:11+01:00
[INFO] ------------------------------------------------------------------------
Thank you in advance for your help.\
EDIT.1
This is how my main method and class look like:
#SpringBootApplication
public class Laboratorium1Application {
public static void main(String[] args) {
SpringApplication.run(Laboratorium1Application.class, args);
}
}
Now, as if thinking about it, something should probably be added here so that the configuration file can be seen.
My project folder:
Only now I noticed that there is no html file. Looking at the examples, I thought that it would generate itself but apparently I was wrong. Someone knows where I can download it from.
You need one additional dependency in your pom.xml file for Spring Boot's (embedded Tomcat) server to start: spring-boot-starter-web Add that and you will be good to go.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
I am having difficulty getting constructor injection using xml working. I have two implementations of a base repository class and I would like to use the xml file to specify which of these to use.
If I switch to annotation (put #Primary in one of the implementing classes) then it works but I don't want to have to change each class file just to switch from one repository to another.
What am I doing wrong?
The base class
package com.iznogoud.cinj.repositories;
import java.util.ArrayList;
public abstract class StringRepository {
public abstract ArrayList<String> getStrings();
}
The two implementing classes:
package com.iznogoud.cinj.repositories;
import java.util.ArrayList;
import org.springframework.stereotype.Repository;
#Repository
public class StringRepositoryImplOne extends StringRepository{
public StringRepositoryImplOne() {}
public ArrayList<String> getStrings() {
ArrayList<String> result = new ArrayList<String>();
result.add("One");
result.add("Un");
result.add("Eins");
return result;
}
}
...and...
package com.iznogoud.cinj.repositories;
import java.util.ArrayList;
import org.springframework.stereotype.Repository;
#Repository
public class StringRepositoryImplTwo extends StringRepository{
public StringRepositoryImplTwo() {}
public ArrayList<String> getStrings() {
ArrayList<String> result = new ArrayList<String>();
result.add("Two");
result.add("Deux");
result.add("Zwei");
return result;
}
}
The controller where I want to inject one of the two repositories above:
package com.iznogoud.cinj.controllers;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;import
org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.iznogoud.cinj.repositories.StringRepository;
#RestController
#RequestMapping("/cinj")
public class AController {
private StringRepository repository;
public AController(StringRepository _r) {
repository = _r;
}
#GetMapping(path="/test", produces = MediaType.APPLICATION_JSON_VALUE)
List<String> getTimeSlots(HttpSession _session) throws IllegalArgumentException, ParseException {
ArrayList<String> availableStrings = repository.getStrings();
return availableStrings;
}
}
The Application class
package com.iznogoud.cinj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.SpringVersion;
#SpringBootApplication
#ImportResource("applicationContext.xml")
public class CinjApplication {
public static void main(String[] args) {
System.err.println("Spring version: " + SpringVersion.getVersion());
SpringApplication.run(CinjApplication.class, args);
}
}
The XML configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="acont" class="com.iznogoud.cinj.controllers.AController">
<constructor-arg ref="sr1"/>
</bean>
<bean id="sr1" class="com.iznogoud.cinj.repositories.StringRepositoryImplOne" primary="true"/>
<bean id="sr2" class="com.iznogoud.cinj.repositories.StringRepositoryImplTwo" />
</beans>
The pom.xml (generated by Spring Initializr and not modified):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.iznogoud</groupId>
<artifactId>cinj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cinj</name>
<description>Constructor injection</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-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>
And finally, the error msg (the short version):
mvn clean spring-boot:run
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< com.iznogoud:cinj >-----------------------
[INFO] Building cinj 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]------------------------------ ---
[INFO]
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) # cinj ---
[INFO] Deleting D:\Users\c82ssim\eclipse-workspace\so_01\target
[INFO]
[INFO] >>> spring-boot-maven-plugin:2.1.6.RELEASE:run (default-cli) > test- compile # cinj >>>
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) # cinj ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) # cinj ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 5 source files to D:\Users\c82ssim\eclipse-work space\so_01\target\classes
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) # cinj ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory D:\Users\c82ssim\eclipse- workspace\so_01\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) # cinj ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to D:\Users\c82ssim\eclipse- workspace\so_01\target\test-classes
[INFO]
[INFO] <<< spring-boot-maven-plugin:2.1.6.RELEASE:run (default-cli) < test- compile # cinj <<<
[INFO]
[INFO]
[INFO] --- spring-boot-maven-plugin:2.1.6.RELEASE:run (default-cli) # cinj - --
Spring version: 5.1.8.RELEASE
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.6.RELEASE)
2019-08-01 11:41:27.466 INFO 10612 --- [ main] com.iznogoud.cinj.CinjApplication : Starting CinjApplication on E82AAT4014 with PID 10612 (D:\Users\c82ssim\eclipse- workspace\so_01\target\classes started by c82ssim in D:\Users\c82ssim\eclipse- workspace\so_01)
2019-08-01 11:41:27.470 INFO 10612 --- [ main] com.iznogoud.cinj.CinjApplication : No active profile set, falling back to default profiles: default
2019-08-01 11:41:28.482 INFO 10612 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.hateoas.config.HateoasConfiguration' of type [org.springframework.hateoas.config.HateoasConfiguration$$EnhancerBySpringCGLIB$$bbc50a5] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-08-01 11:41:28.943 INFO 10612 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8084 (http)
2019-08-01 11:41:28.969 INFO 10612 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-08-01 11:41:28.970 INFO 10612 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-08-01 11:41:29.078 INFO 10612 --- [ main] o.a.c.c.C. [Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-08-01 11:41:29.078 INFO 10612 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1472 ms
2019-08-01 11:41:29.823 INFO 10612 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-08-01 11:41:29.925 WARN 10612 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$Enab leWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'acont' method
java.util.List<java.lang.String> com.iznogoud.cinj.controllers.AController.getTimeSlots(javax.servlet.http.HttpSe ssion) throws java.lang.IllegalArgumentException,java.text.ParseException
to {GET /cinj/test, produces [application/json]}: There is already 'AController' bean method
java.util.List<java.lang.String> com.iznogoud.cinj.controllers.AController.getTimeSlots(javax.servlet.http.HttpSe ssion) throws java.lang.IllegalArgumentException,java.text.ParseException mapped.
Update 1:
If I change the controller annotation to this:
#RestController(value="acont")
I get this exception:
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.1.6.RELEASE:run (default-cli) on project cinj: An exception occurred while running. null: InvocationTargetException: Configuration problem: Failed to register bean definition with name 'acont'
[ERROR] Offending resource: class path resource [applicationContext.xml]; nested exception is
org.springframework.beans.factory.support.BeanDefinitionOverrideException:
Invalid bean definition with name 'acont' defined in class path resource
[applicationContext.xml]: Cannot register bean definition [Generic bean: class
[com.iznogoud.cinj.controllers.AController]; scope=; abstract=false;
lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true;
primary=false; factoryBeanName=null; factoryMethodName=null;
initMethodName=null; destroyMethodName=null; defined in class path resource
[applicationContext.xml]] for bean 'acont': There is already [Generic bean:
class [com.iznogoud.cinj.controllers.AController]; scope=singleton;
abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in
file
[D:\Users\c82ssim\eclipse-
workspace\so_01\target\classes\com\iznogoud\cinj
\controllers\AController.class]]
bound.here
If the issue is about the ambigious method in the bean named "acont", maybe you have to name it:
#Controller("/acont")
public class AController {...}
By default the bean is detected by type in spring.
In your case you are injecting directly by abstract class.
private StringRepository repository;
In this case you need to use #Qualifier to indicate which bean you are exactly referring to.
#Repository("ImplTwo)
public class StringRepositoryImplTwo extends StringRepository{
Simillary,
#Repository("ImplOne)
public class StringRepositoryImplOne extends StringRepository{
And update your dependency injection as,
#Qualifier("ImplTwo") // or "ImplOne" as per your requirement
private StringRepository repository;
Or as you are using constructor injection than do following,
private StringRepository repository;
public AController(#Qualifier("ImplTwo") StringRepository _r) {
repository = _r;
}