MockMvc returned HttpMessageNotWritableException with application/json - java

I have a rest endpoint with spring 2.3.4.RELEASE
When I run test for controller with MockMvc I received
w.s.m.s.DefaultHandlerExceptionResolver : Resolved
[org.springframework.http.converter.HttpMessageNotWritableException:
No converter for [class com.example.myexample.model.User] with preset
Content-Type 'application/json']
#SpringBootTest(classes = UserController.class)
#ExtendWith(SpringExtension.class)
#AutoConfigureMockMvc
public class UserControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private UserRepository userRepository;
private static final String GET_USERBYID_URL = "/users/{userId}";
#Test
public void shouldGetUserWhenValid() throws Exception {
Address address = new Address();
address.setStreet("1 Abc St.");
address.setCity("Paris");
User userMock = new User();
userMock.setFirstname("Lary");
userMock.setLastname("Pat");
userMock.setAddress(address);
when(userRepository.findById(1)).thenReturn(Optional.of(userMock));
mockMvc.perform(get(GET_USERBYID_URL, "1").accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk());
}
}
#RestController
#RequestMapping(path = "/users")
#Slf4j
public class UserController {
#Autowired
private UserRepository userRepository;
#GetMapping(value = "/{userId}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(#PathVariable("userId") Integer userId) {
log.info("Getting user with id={}", userId);
final Optional<User> userOptional = userRepository.findById(userId)
return userOptional.map(value -> ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(value))
.orElseGet(() -> ResponseEntity.noContent()
.build()).ok()
.body(userOptional.get());
}
}
#Data
public class User {
private String firstname;
private String lastname;
private Address address;
}
#Data
public class Address {
private String street;
private String city;
}
#Repository
public interface UserRepository extends CrudRepository<User, Integer> {
}
I've read other article that recommended to added jackson dependency, but this doesn't work for me.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.3</version>
</dependency>
This 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.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>myexample</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR8</spring-cloud.version>
<lombok.version>1.18.12</lombok.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-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.3</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
If I run the application and test it through postman, the endpoint works fine.
Any ideas why I get this error message on my rest controller test?

The problem lies in your #SpringBootTest, when you added classes = UserController.class , it tells spring to create a context with UserController.class. So it create spring context only with UserController. As a result only your controller bean is created and other beans needed for Http Message Converting is not created. So one solution is removing classes = UserController.class from #SpringBootTest.
#SpringBootTest
#ExtendWith(SpringExtension.class)
#AutoConfigureMockMvc
Now you should have no problem running the tests.
But this comes with another problem, now this will load the full spring context which is not needed for only Controller Layer Testing. It will also increase the time of your unit tests.
To solve this problem , spring has another annotation #WebMvcTest . If you annotate yous tests with #WebMvcTest, Spring Boot instantiates only the web layer rather than the whole context. You can also choose to instantiate only one controller. For example,
#ExtendWith(SpringExtension.class)
#WebMvcTest(UserController.class)
public class UserControllerTest {
}
This should solve your problem.

Apparently I put the UserControllerTest in a wrong package name.
It's working now after I put the UserControllerTest in the same package name as the UserController.

Related

Spring does not see repository during scan on app start

Have sandbox springboot app. Decided to try reactive approach, postgres is used as database, I added r2dbc to the project to make my repository reactive. Here is my code:
#SpringBootApplication
public class Springboot2Application {
public static void main(String[] args) {
SpringApplication.run(Springboot2Application.class, args);
}
}
#Repository
public interface ToDoRepository extends
ReactiveCrudRepository<ToDo,String> {
}
#RestController
#RequestMapping("/api/v1")
public class ToDoController {
private final ToDoRepository repository;
public ToDoController(ToDoRepository repository) {
this.repository = repository;
}
#GetMapping(value = "/to-do", produces = {
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE,
MediaType.TEXT_XML_VALUE})
public ResponseEntity<Flux<ToDo>> getToDos(#RequestHeader
HttpHeaders headers){
return ResponseEntity.ok().body(repository.findAll());
}
}
#Data
#RequiredArgsConstructor
#Entity
#Table(name = "todo")
public class ToDo {
#Id
#NotNull
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid")
private String id;
#NotNull
#NotBlank
private String description;
#CreationTimestamp
private Timestamp created;
#UpdateTimestamp
private Timestamp modified;
private boolean completed;
}
r2dbc config:
#Configuration
#EnableR2dbcRepositories(basePackages =
"com.springboot2.repository")
public class R2DBCConfig extends AbstractR2dbcConfiguration {
#Bean
public ConnectionFactory connectionFactory() {
return ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(DRIVER, "postgresql")
.option(HOST, "localhost")
.option(PORT, 5432)
.option(USER, "admin")
.option(PASSWORD, "admin")
.option(DATABASE, "springdb")
.build());
}
}
On application start I'm getting:
Description:
Parameter 0 of constructor in com.springboot2.controller.ToDoController required a bean of type 'com.springboot2.repository.ToDoRepository' that could not be found.
Action:
Consider defining a bean of type 'com.springboot2.repository.ToDoRepository' in your configuration.
I tried to add #ComponentsScan, tried to move ToDoRepository to the root near Springboot2Application, I dont understand why Spring doesn't see repository interface
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.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot2</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
<spring-cloud.version>2021.0.3</spring-cloud.version>
<!-- <spring-shell.version>2.1.0</spring-shell.version>-->
</properties>
<dependencies>
<!-- DB,ORM, and plugins-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</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-data-r2dbc</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-postgresql</artifactId>
<version>0.8.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- Reactive libs-->
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>
</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>
My guess the reason is that you have added r2dbc driver to your project, but haven't added spring-boot-starter-data-r2dbc
So, consider this dependency in your pom.xml file (this is the latest version at the time of writing this answer) :
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-r2dbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
<version>3.0.2</version>
</dependency>
EDIT:
Also you can try to use #EnableR2dbcRepositories and specify the package with your repository.
One more possible way to solve this is to extend your repository from R2dbcRepository, instead of ReactiveCrudRepository
This may help when you have multiple spring data reactive modules (r2dbc and something else) being used in the same project. Since ReactiveCrudRepository is a generic interface Spring does not know how to properly configure these beans.

(Resolvido) Mock Mvc is always null

I was trying to implement a controller test to guarantee that it would return the http 200 code, but when trying to run the test I received a NullPointerException exception.
Debugging the code I found that the MockMvc was null.
I already tried to add annotations like #SpringBootTest, #AutoConfigureMockMvc, #WebMvcTest, #ExtendWith and the MockMvc was still null and now I don't know what else to do to solve this problem
Note: I'm learning about these test things so if there's something bad in the code I'd appreciate it if you let me know
Here is my test code:
`
#ExtendWith(MockitoExtension.class)
#WebMvcTest(BookController.class)
#AutoConfigureMockMvc
#SpringBootTest
public class TestControlBook {
#Autowired
private MockMvc mockMvc;
#Test
public void testListBooks() throws Exception{
Response ResultActions = mockMvc.perform(MockMvcRequestBuilders.get("/api/books/list"));
response.andExpect(MockMvcResultMatchers.status().isOk());
}
}
here is my controller code:
`#RestController
#RequestMapping("/api/books")
public class BookController {
private BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
#GetMapping("/list")
private ResponseEntity<Object> listBooks(){
try {
return ResponseEntity.status(HttpStatus.OK).body(bookService.listBooks());
}
catch (Exception e){
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred while trying to list the books, please try again later");
}
}
}
and 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 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.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tdd</groupId>
<artifactId>exemplo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>TDD Exemplo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.0.0</version>
</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</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.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>4.6.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>`
```
I managed to solve the problem, what was happening was that the annotations were in conflict, causing the MockMvc not to be assigned. In addition, I changed some things so that the code was more readable and better.
The code is now like this:
#WebMvcTest(LivroController.class)
#AutoConfigureMockMvc
public class LivroControlerTeste {
#Autowired
private MockMvc mockMvc;
#MockBean
private LivroService livroService;
#Test
public void testarListarLivros() throws Exception{
MvcResult mvcResult = mockMvc.perform(get("/api/livros/listar"))
.andExpect(status().isOk()).andReturn();
}
}

Facing o.s.web.servlet.PageNotFound : No mapping for GET / problem in my spring boot project

I am trying to implement REST microservices using Spring Boot in my project. I have created a controller for login page and also created repository.
But while hitting URL I am facing this issue o.s.web.servlet.PageNotFound: No mapping for GET /
Main Class
#ComponentScan(basePackages = {"com.springboot.controller.repository"})
#EntityScan(basePackages="com.springboot.controller.model")
#EnableJpaRepositories(basePackages="com.springboot.controller.repository")
#SpringBootApplication
public class CunsultustodayWebServicesApplication {
public static void main(String[] args) {
SpringApplication.run(CunsultustodayWebServicesApplication.class, args);
}
}
Controller
#RestController
#ComponentScan
#Controller
public class LoginController {
#Autowired(required=true)
private UserRepo userrepo;
#RequestMapping("/")
public String checkMVC()
{
return "Login";
}
#RequestMapping("/login")
public String loginHome(#RequestParam("email") String email, #RequestParam("password") String password, Model model)
{
User u = null;
try {
u= userrepo.findByEmail(email);
}
catch(Exception ex) {
System.out.println("User Not Found!!!");
}
if(u!=null) {
model.addAttribute("email", email);
return "HomePage";
}
return "Login";
}
}
Repository
#Service("UserRepo")
public interface UserRepo extends JpaRepository<User,Integer> {
User findByEmail(String email);
}
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot.controller</groupId>
<artifactId>cunsultustoday-web-services</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cunsultustoday-web-services</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Please help me to find solution. Thank You
Your controller is probably not being picked up by the ComponentScan because you have limited to the package for the scan.
Try this:
// note #ComponentScan is removed as it is included already in #SpringBootApplication
#EnableJpaRepositories
#SpringBootApplication
public class CunsultustodayWebServicesApplication {
...
And This:
// note #Controller and #CompnentScan are removed
#RestController
public class LoginController {

spring validation for requestparam not working

I am trying to validate my parameter in controller using #Min(1) annotation. When I test it in unit test, it comes as 200. I am not sure what I am doing wrong. Here is my code:
Controller:
#GetMapping(produces = "application/json")
public Response search(#RequestParam(name = "firstname", required = false) String firstName,
#RequestParam(name = "lastname", required = false) String lastName, #RequestParam("ibid") #Min(1) long ibId,
#RequestParam(name = "workstationids", required = false) List<Long> workstationIds,
#RequestParam("timerange") int timeRange,
#RequestParam(name = "receivingstatus", required = false) String receivingStatus,
#RequestParam(name = "displaystart", required = false) Integer displayStart,
#RequestParam(name = "displaylength", required = false) Integer displayLength,
#RequestParam("timezone") #NotBlank String timeZone) {
...
...
Test:
#Test
public void searchWithInvalidParams() throws Exception {
mockMvc.perform(get(BASE_URL)
.param(COLUMN_IB_ID, INVALID_IB_ID_VALUE) //invalid ib id is "-1"
.param(COLUMN_TIME_RANGE, TIME_RANGE_VALUE)
.param(COLUMN_TIME_ZONE, TIME_ZONE)
.andExpect(status().isBadRequest());
}
I am expecting it to return 400, but result is 200.
Update:
So I added #Validated in controller and added dependency to pom and it still doesn't work(still 200)
my pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.nuance.powershare</groupId>
<artifactId>psh-app-dispatch-reporter</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>psh-app-dispatch-reporter-service</artifactId>
<properties>
<sqljdbc4.version>4.0.0</sqljdbc4.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.nuance.powershare</groupId>
<artifactId>psh-lib-dispatch-reporter-model</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>${sqljdbc4.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
You have done the following 2 steps correctly:
Included the hibernate validator to the pom.xml
Added #Validated annotation to the controller
Two more steps are required. Can you do these two in addition to above:
Add one more entry to the pom.xml (not sure about why the javax.el is needed)
<dependency>
<groupId>org.glassfish </groupId>
<artifactId>javax.el </artifactId>
<version>3.0.1-b11 </version>
</dependency>
Add the following to your Java Configuration class
#Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
(refer - https://www.baeldung.com/spring-validate-requestparam-pathvariable)
Starting with Boot 2.3, the required steps for #RequestParam and #PathVariable validation are:
Add dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Add #Validated to controller class
Source: https://www.baeldung.com/spring-boot-bean-validation

I tried to run the application and It fails with required beans

Description:
Field userRepository in com.rst.boot.services.impl.UserServiceImpl required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
This is my service class:
#Service
public class UserServiceImpl implements UserServices {
#Autowired
private UserRepository userRepository;
#Override
public List<UserDTO> findAllUsers() {
List<UserDTO> allusers= userRepository.findAll();
return allusers;
}
#Override
public String saveUser(UserDTO userdata) {
userRepository.save(userdata);
return "Data saved";
}
}
<?xml version="1.0" encoding="UTF-8"?>
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>org.example</groupId>
<artifactId>Leaning</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Springboot Demo App</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
First, in your bootstrap class make sure you have the #EnableAutoConfiguration annotation. If you have #SpringBootApplication, should be enough, since the latter is annotated with the first.
#SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
Second, make sure that UserRepository extends JpaRepository or CrudRepository:
public interface UserRepository extends JpaRepository<User, Long> {}
Last, check that you have the correct dependency in your maven or gradle configuration. E.g.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Categories