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>
Related
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.
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.
I created a very basic Spring Boot project with REST APIs. I tried connecting it to my Angular app but it was getting some CORS security error so I switched to Postman. I'm trying to test it using Postman but I keep receiving a 404 not found error on Postman. Why am I not able to connect to my backend and post to tester function?
controller
package controllers;
#RestController
public class Handler {
#PostMapping("/tester/{id}")
public String tester(#PathVariable(value="id")long userid ){
System.out.println("in tester");
System.out.println(userid);
return "succeeded test";
}
}
main
package halloween.contest;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,
SecurityAutoConfiguration.class})
public class ContestApplication {
public static void main(String[] args) {
SpringApplication.run(ContestApplication.class, args);
}
}
application.properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
spring.data.rest.base-path=/
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.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>halloween</groupId>
<artifactId>contest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>contest</name>
<description>halloween picture contest</description>
<properties>
<java.version>11</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
console
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.6)
2021-10-26 15:44:12.823 INFO 18760 --- [ main] halloween.contest.ContestApplication : Starting ContestApplication using Java 1.8.0_144 on DESKTOP-VB80TS0 with PID 18760 (C:\Users\Sergio Rodríguez\Documents\Halloween\contest\target\classes started by Sergio Rodríguez in C:\Users\Sergio Rodríguez\Documents\Halloween\contest)
2021-10-26 15:44:12.827 INFO 18760 --- [ main] halloween.contest.ContestApplication : No active profile set, falling back to default profiles: default
2021-10-26 15:44:16.013 INFO 18760 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-10-26 15:44:16.043 INFO 18760 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-10-26 15:44:16.043 INFO 18760 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.54]
2021-10-26 15:44:16.310 INFO 18760 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-10-26 15:44:16.310 INFO 18760 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3372 ms
2021-10-26 15:44:19.326 INFO 18760 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-10-26 15:44:19.342 INFO 18760 --- [ main] halloween.contest.ContestApplication : Started ContestApplication in 7.201 seconds (JVM running for 7.946)
2021-10-26 15:45:45.138 INFO 18760 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-10-26 15:45:45.139 INFO 18760 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-10-26 15:45:45.157 INFO 18760 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 17 ms
equivalent cURL command
curl --location --request POST 'localhost:8080/tester/69'
Postman
Answering my own question now that I figured it out. It wasn't apparent based on the code I provided but I'll leave my post for future help (wording helps).
the problem was visibility of packages. I had my controller class in a different package from the main class.
To fix the CORS issue, next to #PostMapping("/tester/{id}") add #CrossOrigin(origins = "http://localhost:<port>") where port is the port from which your Angular app is running.
In your target URL, make sure you've included the default Spring Boot port of 8080, e.g. http://localhost:8080/tester/123 and obviously, please double check that you're doing a POST and not a GET.
got a similar problem..then added the below annotations on top of springbootappication where main() exists, then it's working fine for me.
#EnableWebMvc
#ComponentScan("com.*.*")
Also in postman make the below changes...
Disable/uncheck File --> Proxy --> "Use the system proxy"
Disable/uncheck File --> General --> "SSL Certificate Verification"
I am started building a spring boot application but i am getting this type of error "Whitelabel Error Page - This application has no configured error view, so you are seeing this as a fallback."
I created the project from https://start.spring.io/.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.3.RELEASE)
2020-09-09 16:12:00.389 INFO 19440 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication on ***** with PID 19440 (C:\Users\m.petraglia\Desktop\demo\target\classes started by m.petraglia in C:\Users\m.petraglia\Desktop\demo)
2020-09-09 16:12:00.391 INFO 19440 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2020-09-09 16:12:01.024 DEBUG 19440 --- [ main] o.s.w.r.handler.SimpleUrlHandlerMapping : Patterns [/webjars/**, /**] in 'resourceHandlerMapping'
2020-09-09 16:12:01.118 DEBUG 19440 --- [ main] o.s.w.r.r.m.a.ControllerMethodResolver : ControllerAdvice beans: none
2020-09-09 16:12:01.138 DEBUG 19440 --- [ main] o.s.w.s.adapter.HttpWebHandlerAdapter : enableLoggingRequestDetails='false': form data and headers will be masked to prevent unsafe logging of potentially sensitive data
2020-09-09 16:12:01.961 INFO 19440 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2020-09-09 16:12:01.967 INFO 19440 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 1.837 seconds (JVM running for 2.132)
2020-09-09 16:12:07.977 DEBUG 19440 --- [ctor-http-nio-2] o.s.w.s.adapter.HttpWebHandlerAdapter : [22183960-1] HTTP GET "/hello"
2020-09-09 16:12:07.998 DEBUG 19440 --- [ctor-http-nio-2] o.s.w.r.handler.SimpleUrlHandlerMapping : [22183960-1] Mapped to ResourceWebHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"]
2020-09-09 16:12:08.000 DEBUG 19440 --- [ctor-http-nio-2] o.s.w.r.resource.ResourceWebHandler : [22183960-1] Resource not found
2020-09-09 16:12:08.025 DEBUG 19440 --- [ctor-http-nio-2] org.springframework.web.HttpLogging : [22183960-1] Resolved [ResponseStatusException: 404 NOT_FOUND] for HTTP GET /hello
2020-09-09 16:12:08.031 DEBUG 19440 --- [ctor-http-nio-2] org.springframework.web.HttpLogging : [22183960-1] Writing "<html><body><h1>Whitelabel Error Page</h1><p>This application has no configured error view, so you (truncated)...
2020-09-09 16:12:08.042 DEBUG 19440 --- [ctor-http-nio-2] o.s.w.s.adapter.HttpWebHandlerAdapter : [22183960-1] Completed 404 NOT_FOUND
DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#GetMapping("/hello")
public String hello(#RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.demo</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Project structure:
I don't understand what is the problem.
Try adding #RestController annotation to the class
maybe you should use html file to run it in browser in my opinion,and also if you use thymeleaf include the dependencies as well
I 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;
}