404 running through Spring tutorial - java

I'm working through a Spring tutorial at http://spring.io/guides/gs/validating-form-input/, and get a 404 upon attempting to access the localhost root.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Aug 06 02:36:15 CDT 2014
There was an unexpected error (type=Not Found, status=404).
I modified the workflow a bit to use Eclipse's Maven project settings. The steps I took, that were different from the tutorial, in order:
Created a Maven Project in Eclipse
Replaced the pom.xml that was generated with the one from the tutorial
The tutorial instruct to have the template HTML files in resources/templates, and Spring threw this exception (quite a few internal exceptions, actually), Caused by: java.lang.IllegalStateException: Cannot find template location: class path resource [templates/] (please add some templates or check your Thymeleaf configuration)
To resolve, I moved the templates form.html and results.html to /templates on the classpath.
I checked with the debugger the WebController class, and none of it's code is being hit. I don't believe it is a local configuration issue, because the completed tutorial in their git repo behaves as expected.
If anyone has any insight at all, it would be much appreciated. Thank you!
These are the files from my non-working attempt.
WebController.java
package hello;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
public class WebController extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/results").setViewName("results");
}
#RequestMapping(value="/", method=RequestMethod.GET)
public String showForm(Person person) {
return "form";
}
#RequestMapping(value="/", method=RequestMethod.POST)
public String checkPersonInfo(#Valid Person person, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
return "redirect:/results";
}
}
Application.java
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
Person.java
package hello;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Person {
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [name=")
.append(name)
.append(", age=")
.append(age)
.append("]");
return builder.toString();
}
#Size(min=2, max=30)
private String name;
#NotNull
#Min(18)
private Integer age;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-validating-form-input</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.4.RELEASE</version>
</parent>
<properties>
<!-- use UTF-8 for everything -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<start-class>hello.Application</start-class>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>http://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>http://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>

There is no #Controller on your controller. As far as Spring is concerned this class is just a simple pojo that it shouldn't care about: it's not defined anywhere and it's not picked up by classpath scanning since it does not have the proper annotation on it.

Related

Maven Spring Boot App Failing to Start from VS Code

Attempting to write a Java RESTful API When I run mvn clean install I build no problem. When I run mvn spring-boot run I get the following runtime error. I have included the pom.xml and classes that I think are relevant. I also have a service layer and entity class not listed, though I don't think they are the issue. I can add if maybe someone would like to see them as well. Any help would be greatly appreciated.Thank you in advance.
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:161) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
below is code that I think could potentially be causing the problem:
pom.xml
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.myproject</groupId>
<artifactId>Java_API</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>2.3.3.RELEASE</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.0.2</version>
</plugin>
</plugins>
</build>
</project>
Main.java
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Main {
public static void main(String[] args)
{
SpringApplication.run(myController.class,args);
}
}
myController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class myController {
#Autowired
private EmployeeService employeeService;
#GetMapping("/employee/{id}")
public Employee getEmployee(#PathVariable int id) {
return employeeService.getEmployee(id);
}
#PostMapping("/employee")
public void createEmployee(#RequestBody Employee employee) {
EmployeeService.createEmployee(employee);
}
}
I have tried only having starter-web instead of both starter-web and starter-tomcat, but it yields the same result. The versioning seems right.
tried adding <scope>provided</scope>, granted I'm not entirely sure what it does.
A number of other things that may come to me, blanking on everything I have tried. Really stumped on what it does not like.
Change Main.java
change SpringApplication.run(myController.class,args);
to
SpringApplication.run(Main.class, args);
public static void main(String[] args)
{
//SpringApplication.run(myController.class,args);
SpringApplication.run(Main.class, args);
}
pom.xml
you can remove spring-boot-starter-tomcat
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.myproject</groupId>
<artifactId>Java_API</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<!--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>2.3.3.RELEASE</version>
<scope>provided</scope>
</dependency>
-->
</dependencies>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.0.2</version>
</plugin>
</plugins>
</build>
</project>
package and run
mvn clean package spring-boot:run
test
curl http://localhost:8080/employee/22
I can't get enough information from your question. I change my test code:
myController.java
package com.example.myproject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class myController {
//#Autowired
//private EmployeeService employeeService;
#GetMapping("/employee/{id}")
public Employee getEmployee(#PathVariable int id) {
Employee e1=new Employee();
e1.setId(id);
e1.setName("Hello World");
return e1;
//return employeeService.getEmployee(id);
}
#PostMapping("/employee")
public void createEmployee(#RequestBody Employee employee) {
System.out.println("DEBUG-"+ employee.getId()+"\t"+employee.getName());
//EmployeeService.createEmployee(employee);
}
}
Employee.java
package com.example.myproject;
public class Employee {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I use the following code to test on my machine and it can be executed. At the same time, when you change SpringApplication.run(Main.class, args); back to SpringApplication.run(myController.class, args) ;, when executed it throws the same error message as in the question, Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
If there are other error messages generated, it should be part of your EmployeeService. You did not provide enough information.

Consider defining a bean of type '...' in your configuration when using JPARepository

Ive been trying to follow a few basic examples to create a rest api to connect to a local mysql server
However I keep running to this error
Consider defining a bean of type 'org.example.database.MessagesRepository' in your configuration.
Here is my current project layout
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>messagesApi</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Main.java
package org.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
#EnableAsync
#SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
MessagesApi
package org.example.api;
import org.example.models.Messages;
import org.example.database.MessagesRepository;
import org.example.models.MessagesRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#Controller
#RequestMapping("/chats")
public class MessagesApi {
#Autowired
MessagesRepository messagesRepository;
#GetMapping("id")
public ResponseEntity<Messages> getAllChatsById(#RequestBody MessagesRequest messageRequest) {
return new ResponseEntity<>(messagesRepository.findByTextId(messageRequest.getTextId()), HttpStatus.OK);
}
#GetMapping("username")
public ResponseEntity< List<Messages>> getAllChatsByUserName(#RequestBody MessagesRequest messageRequest) {
return new ResponseEntity<>(messagesRepository.findByUserName(messageRequest.getUserName()), HttpStatus.OK);
}
#PostMapping
public ResponseEntity<Long> postMessage(#RequestBody Messages message ){
//make Id
Long id = 1234L;
message.setTextId(id);
messagesRepository.save(message);
return new ResponseEntity<>(id, HttpStatus.CREATED);
}
}
MessagesRespository
package org.example.database;
import org.example.models.Messages;
import org.springframework.data.repository.JpaRepository;
import java.util.List;
public interface MessagesRepository extends JpaRepository<Messages, Long> {
List<Messages> findByUserName(String userName);
Messages findByTextId(Long textId);
}
applications.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=passWord
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Ive tried adding
#EnableJpaRepositories
But kept getting
``Consider defining a bean named 'entityManagerFactory' in your configuration.
When removing
exclude={DataSourceAutoConfiguration.class}
I would get
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
I am not sure where to move forward from here
public interface MessagesRepository extends JpaRepository<Messages, Long> {
rather should be
#Repository
public interface MessagesRepository extends JpaRepository<Messages, Long> {
to make below code work
#Autowired
MessagesRepository messagesRepository;
also exclude from main class
exclude={DataSourceAutoConfiguration.class}
Sometimes spring is not able to scan your entity classes or your configuration classes so use this it will work fine
#SpringBootApplication
#ComponentScan({"org.example"})
#EntityScan("org.example")
#EnableJpaRepositories("org.example")
public class WebServiceApplication extends SpringBootServletInitializer {
}

How to fix 'HTTP-404' error, during GET request in REST web service using spring boot

My sample spring boot REST web service gives 404 error, and I am not sure what went wrong
package com.in28minutes.springboot.studentservices;
#SpringBootApplication
public class StudentServicesApplication {
public static void main(String[] args) {
SpringApplication.run(StudentServicesApplication.class, args);
}
}
package com.in28minutes.springboot.controller;
#RestController
public class StudentController {
#Autowired
private StudentService studentService;
#GetMapping("/students/{studentId}/courses")
public List<Course> retrieveCoursesForStudent(#PathVariable String
studentId) {
return studentService.retrieveCourses(studentId);
}
#GetMapping("/students/{studentId}/courses/{courseId}")
public Course retrieveDetailsForCourse(#PathVariable String studentId,
#PathVariable String courseId) {
return studentService.retrieveCourse(studentId, courseId);
}
}
My Request from POSTMan REST request sender:
http://localhost:8080/students/stu1/courses/course1
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.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.in28minutes.springboot</groupId>
<artifactId>student-services</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>student-services</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-actuator</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>
</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>
Response:
{
"timestamp": "2018-12-28T02:48:00.185+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/students/stu1/courses/course1"
}
As assumed, you have Controller classes in different package com.in28minutes.springboot.controller; and Spring boot main class in different package com.in28minutes.springboot.studentservices;
#SpringBootApplication
By default #SpringBootApplication will only scan from the package of the class that declares this annotation.
This is a convenience annotation that is equivalent to declaring #Configuration, #EnableAutoConfiguration and #ComponentScan.
If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
use #ComponentScan to scan controller package
#ComponentScan(basePackages = {"com.in28minutes.springboot.controller"})
#SpringBootApplication
public class StudentServicesApplication {
public static void main(String[] args) {
SpringApplication.run(StudentServicesApplication.class, args);
}
}
More Info : ref
The issue is resolved, #Component needed to be added to Service class, along with #ComponentScan in the main application class:
package com.in28minutes.springboot.service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.stereotype.Component;
import com.in28minutes.springboot.model.Course;
import com.in28minutes.springboot.model.Student;
#Component
public class StudentService {
public List<Course> retrieveCourses(String studentId) {
Map<String, Course> courses = Student.getStudentObj(studentId).getCourses();
List<Course> courseList =
courses.values().parallelStream().collect(Collectors.toList());
return courseList;
}
public Course retrieveCourse(String studentId, String courseId) {
return Student.getStudentObj(studentId).getCourses().get(courseId);
}
}
package com.in28minutes.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("com.in28minutes.springboot")
public class StudentServicesApplication {
public static void main(String[] args) {
SpringApplication.run(StudentServicesApplication.class, args);
}
}

How to make Spring's #Autowired to work in JUnit 5 extensions? [duplicate]

This question already has an answer here:
JUNIT 5: Inject spring components to custom TestTemplateInvocationContextProvider
(1 answer)
Closed 4 years ago.
I have a Spring Boot application, and I am trying to use #Autowired in a JUnit 5 extension. However, I cannot get it to work. (The #Autowired field is null.) Can anybody help?
Below is code that demonstrates the problem I'm having (the important parts are SomeExtension and SomeTest. As written, mvn test causes the test to fail in beforeEach. Sorry if I'm including too much.
src/test/java/somepackage/SomeExtension.java:
package somepackage;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.assertNotNull;
#ExtendWith(SpringExtension.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SomeExtension implements BeforeEachCallback {
#Autowired
SomeBean bean;
#Override
public void beforeEach(ExtensionContext context) {
assertNotNull(bean);
}
}
src/test/java/somepackage/SomeTest.java:
package somepackage;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
#ExtendWith(SpringExtension.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ExtendWith(SomeExtension.class)
class SomeTest {
#Test
void nothingTest() {
}
}
src/main/java/somepackage/SomeBean.java
package somepackage;
import org.springframework.stereotype.Component;
#Component
public class SomeBean {
}
src/main/java/somepackage/MainClass.java
package somepackage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MainClass {
public static void main(String[] args) {
SpringApplication.run(MainClass.class, args);
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>fooGroupId</groupId>
<artifactId>barArtifactId</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<!-- Don't include Junit 4 -->
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<!--
This is copied from https://junit.org/junit5/docs/current/user-guide/#running-tests-build-maven
This allows the surefire plugin to be able to find Junit 5 tests, so `mvn test` works.
-->
<artifactId>maven-surefire-plugin</artifactId>
<version>2.21.0</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
I'm also having similar issues with #Value. If the solution also works for that, it would be great.
Thank you.
JUnit 5 extensions can not operate on other extensions, just on test classes.
So...
#ExtendWith(SpringExtension.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SomeExtension implements BeforeEachCallback {
#Autowired
SomeBean bean;
#Override
public void beforeEach(ExtensionContext context) {
assertNotNull(bean);
}
}
#ExtendWith(SpringExtension.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ExtendWith(SomeExtension.class)
class SomeTest {
#Test
void nothingTest() {
}
}
... can not work. This would:
public class SomeExtension implements BeforeEachCallback {
#Override
public void beforeEach(ExtensionContext context) {
// [...]
}
}
#ExtendWith(SpringExtension.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ExtendWith(SomeExtension.class)
class SomeTest {
#Autowired
SomeBean bean;
#Test
void nothingTest() {
}
}
If you can explain why you need a bean in your extension, we may be able to help you find a fix for that, too.

Dynamic webapp project with Maven in Eclipse with weblogic server

I am trying to create a simple REST project with Maven in Eclipse.
I have created a new Dynamic Webapp Project and than right click --> configure/ convert Maven Project.
Now If I create a simple index.html with only one h1, it works.
So I created the GreetingController.java:
package resources;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
and the model: Greeting.java
package resources;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
and the pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-rest-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
<packaging>war</packaging>
</project>
If I go to http://localhost:7001/demo/greeting , it doesn't work (404). Same problem with http://localhost:7001/greeting .
I think the problem is that the server doesn't map the annotation.
The RequestMapping value should not include the context root. Change the value to
#RequestMapping("/greeting")

Categories

Resources