Spring Boot WebFlux test not finding MockMvc - spring

Problem
I'm trying to run a simple spring boot test and I'm getting errors that suggest it can't MockMvc at runtime. Documentation suggests I'm using the correct annotations and I created my pom.xml using start.spring.io. Not sure why its having issues.
Error:
No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc'
TestCode
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class MyWebApplicationTests {
#Autowired
MockMvc mockMvc;
#Test
public void Can_Do_Something() throws Exception {
mockMvc.perform(get("/hello-world")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
}
Documentation:
I was using this doc as a reference ->
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-with-mock-environment
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>com.mywebapp</groupId>
<artifactId>webapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>my-webapp</name>
<description>Backend application</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.M1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>10</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>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

As this Question seems to appear at the top of search lists when people are trying to test their endpoints after they've switched to Spring WebFlux, I'll add what I was able to determine here. (It should be noted that in the past I was having an incredibly hard time getting the WebTestClient to function with RestController annotated endpoints. But this code works. I think I was missing a dependency and it wasn't clear.)
MyService.java
#Service
public class MyService {
public String doSomething(String input) {
return input + " implementation";
}
}
MyController.java
#RestController
#RequestMapping(value = "/api/v1/my")
public class MyController {
#Autowired
private MyService myService;
#RequestMapping(value = "", method = RequestMethod.POST, consumes = {APPLICATION_JSON_VALUE})
public ResponseEntity<Mono<String>> processPost(#RequestBody String input)
{
String response = myService.doSomething(input);
return ResponseEntity.ok(Mono.just(response));
}
TestMyController.java
#ExtendWith(SpringExtension.class)
#WebFluxTest(MyController.class)
public class TestMyController {
#Autowired
private WebTestClient webTestClient;
#MockBean
private MyService myService;
#Test
public void testPost() throws Exception {
// Setup the Mock MyService. Note the 'mocked' vs 'implementation'
when(myService.doSomething(anyString())).thenAnswer((Answer<String>) invocation -> {
String input = invocation.getArgument(0);
return input + " mocked";
});
String response = webTestClient.post()
.uri("/api/v1/my")
.body(BodyInserters.fromObject("is"))
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.returnResult(String.class)
.getResponseBody()
.blockFirst();
assertThat(response).matches("is mocked");
}
}
The dependencies that can cause issues that are hard to diagnose appear to be from reactor-test. So if the WebTestClient is not working, make sure that dependency exists.
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.1.5.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.2.9.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>jackson-module-kotlin</artifactId>
<groupId>com.fasterxml.jackson.module</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.4.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>0.45</version>
<scope>test</scope>
</dependency>

As pointed out by M. Deinum MockMvc isn't loaded for the WebFlux configuration in Spring Boot. You need to use WebTestClient instead. So replace AutoConfigureMockMvc with AutoConfigureWebTestClient and utilize the the webTestClient methods in its place.
One thing to note is that this is making actual web calls behind the scenes and will start the server. MockMVC does not start the server. What is the difference between MockMvc and WebTestClient?

Related

Spring Social LinkedIn : 'org.springframework.social.linkedin.api.LinkedIn' that could not be found

I'm trying to create a Spring Social application with Spring Boot and Im facing issues starting it . I have gone through Spring social documentation and Spring Social sample projects searching around the web. Whatever Ive tried did not work and I was wandering if someone can help me with this here .
LinkedInController
package com.example.demo;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.linkedin.api.LinkedIn;
import org.springframework.social.linkedin.api.ProfileOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/linkedin")
public class LinkedInController {
private static final String LINKEDIN_DISPLAY = "linkedin";
private static final String LINKEDIN_REDIRECT = "redirect:/connect/linkedin";
private LinkedIn linkedIn;
private ConnectionRepository connectionRepository;
public LinkedInController(LinkedIn linkedIn, ConnectionRepository connectionRepository) {
this.linkedIn = linkedIn;
this.connectionRepository = connectionRepository;
}
#GetMapping
public String helloLinkedIn(Model model) {
if (connectionRepository.findPrimaryConnection(LinkedIn.class) == null) {
return LINKEDIN_REDIRECT;
}
ProfileOperations user = linkedIn.profileOperations();
System.out.println(user);
model.addAttribute("linkedInProfile",linkedIn.profileOperations().getUserProfileFull());
return LINKEDIN_DISPLAY;
}
}
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>com.example</groupId>
<artifactId>HCLinkedIn</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>HCLinkedIn</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<start-class>com.example.demo.HcLinkedInApplication</start-class>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-linkedin</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-core</artifactId>
<version>1.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-config</artifactId>
<version>1.1.6.RELEASE</version>
</dependency>
<!-- <dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-security</artifactId>
<version>1.1.6.RELEASE</version>
</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>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
application.properties
spring.social.linkedin.app-id=<<client-key>>
spring.social.linkedin.app-secret=<<client-secret>>
I had the same issue, turns out I forgot to add the OAuth2.0 redirect url.
Log in to your developer's account on linkedin and under the heading OAuth 2.0
There will be an input field for the redirect url called Authorized Redirect URLs:
Add the redirect url..say you are testing using your localhost, put http://localhost:8080/connect/linkedin
replace 8080 by your port and /connect/linkedin by whatever you are using to access the authorization.
Also, incase you haven't specified..add linkedinConnect.html and linkedinConnected.html to your templates/connect

Spring boot Rest Api controller getting 404 error

I'm exposing my services by using Rest in Spring boot. I'm exposing my service with 2 different approach first by using cxf jaxrs dependency and other by spring rest dependency. In first approach i'm getting 404 error when i run my services in postman. But in second approach i'm getting my output. Please help me out.
First approach with cxf jaxrs
#Path("/locations")
public interface LocationRestController {
#GET
public List<Location> getLocations();
}
******************************************
#RestController
public class LocationRestControllerImpl implements LocationRestController {
#Autowired
LocationRepos repos;
#Override
public List<Location> getLocations() {
return repos.findAll();
}}
{
"timestamp": "2018-09-17T03:36:05.283+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/locationweb/locations"
}
Second approach using spring inbuilt dependency
#RestController
#RequestMapping("/locations")
public class LocationRestControllerImpl {
#Autowired
LocationRepos repos;
#GetMapping
public List<Location> getLocations() {
return repos.findAll();
}}
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
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.project.abhishek</groupId>
<artifactId>student</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>student</name>
<description>Student DAL</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
"pom.xml" <version>2.1.0.M2</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>9.0.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
<version>3.2.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
please refer below code for correct implementation
public interface LocationRestController {
public List<Location> getLocations();
}
******************************************
#RestController(value="/locationweb/locations")
public class LocationRestControllerImpl implements LocationRestController {
#Autowired
LocationRepos repos;
#Override
#GetMapping
public List<Location> getLocations() {
return repos.findAll();
}}
{
This line might be the issue
#RestController
public class LocationRestControllerImpl implements LocationRestController {
remove #RestController from the class in 1st approach
Try this example,
https://dzone.com/articles/spring-boot-building-restful-web-services-with-jersey
Most probably you are missing Spring/Jersey integration or Jersey Configuration.
Do add Jersey Configuration for Spring boot to understand Jersey.
Below is the code for Jersey Configuration for convenience.
#Configuration
#ApplicationPath("rest")
public class Config extends ResourceConfig {
public Config() {
}
#PostConstruct
public void setUp() {
register(Controller.class);
}
}
Make sure you have CXF configuration and set as a service bean as if you use #RestController you are actually not implementing CXF so to order to handle requests by CXF, you need to configure CXF server.
#Configuration
public class CXFConfig {
#Autowired
private Bus bus;
#Bean
public Server rsServer() {
final JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
endpoint.setBus(bus);
endpoint.setAddress("/");
endpoint.setServiceBeans(Arrays.asList(LocationRestController ()));
return endpoint.create();
}
#Bean
public LocationRestController locationController() {
return new LocationRestControllerImpl();
}
}
Note: No need to implement a controller, you can have directly controller.

extends WebSecurityConfigurerAdapter Cannot be resolved

I'm using SpringBoot I need use extends WebSecurityConfigurerAdapter for use "CORS".
But When I put "extends WebSecurityConfigurerAdapter" I have error
Description Resource Path Location Type
The type org.springframework.security.authentication.AuthenticationManager cannot be resolved. It is indirectly referenced from required .class files ServiciosConfig.java /tutorial/src/main/java/com/service/configure line 1 Java Problem
I updated pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
With version :
<version>1.5.14.RELEASE</version>
Code:
package com.service.configure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
#Configuration
#EnableWebSecurity
#ComponentScan(basePackages = "com.service.services")
#PropertySource("file:${ruta_properties}")
public class ServiciosConfig extends WebSecurityConfigurerAdapter {
#Value("${usrRest}")
private String usrRest;
#Value("${passRest}")
private String passRest;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated().and().httpBasic().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
// To allow Pre-flight [OPTIONS] request from browser
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser(usrRest).password(passRest).roles("USER");
}
}
The error begins in package com.service.configure; in p When I remove extends , package doesn't errors... But I can't use WebSecurityConfigurerAdapter obvius...
Edit 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>com</groupId>
<artifactId>tutorial</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>tutorial</name>
<description>Project tutorial</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.14.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA Data -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<!-- Tomcat embedded container -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- Data REST -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
change your dependency to use this
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
This will solve teh problem
Finally I found the solution
Add pom.xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
But When I run the program I get other error...
PasswordEncoder mapped for the id “null”
I had the same issue.
I deleted my repo in .m2 folder and rebuild the application in cmd using command :
mvn clean install -U
It worked for me.
In Spring Security 5.7.0-M2 WebSecurityConfigurerAdapter was deprecated.
Refer the below link:
https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

Spring Boot project shows the Login page

I created a Spring boot project with the Spring initializer and only have the starter code so far.
The sample code
#SpringBootApplication
public class EcommerceApplication {
public static void main(String[] args) {
SpringApplication.run(EcommerceApplication.class, args);
}
}
#Controller
#RequestMapping(value = "/")
public class HomeController {
#GetMapping
public String index() {
return "index";
}
}
I expect it to return the index.html page from the templates folder. Instead, I'm redirected to the http://localhost:8080/login address and asked for the username/ password. In the application.properties file, I tried to use the configuration of,
server.port=8080
spring.application.name=Bootstrap Spring Boot
spring.thymeleaf.cache=false
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=testuser
spring.datasource.password=testpassword
server.error.path=/error
server.error.whitelabel.enabled=false
I tried to login with the username testuser and the password testpassword. This doesn't work out.
I use the following pom.xml in the project,
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.online.books</groupId>
<artifactId>Ecommerce</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Ecommerce</name>
<description>Spring Boot Project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>com.h2database</groupId>-->
<!--<artifactId>h2</artifactId>-->
<!--<scope>runtime</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.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
Whats the issue here?
If you don't want login page (from Spring-Security) remove the following dependency from your pom.xml and do maven update to refresh the dependencies on the class path.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Or if you want to use the Spring-Security then on console it will display the default password like below :
Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6
the default username will be user
That is the default behavior. to change this, you have a few options:
You can remove the Spring Boot Security dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
You can desable autoconfiguration. To do so; in your main class, to: #SpringBootApplication append: (exclude = { SecurityAutoConfiguration.class }) so that it looks like:
#SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public static void main(String[] args) {
SpringApplication.run(SpringBootSecurityApplication.class, args);
}
}
you can also do this from the application.properties file
For more information on desableing Auto-Configuration and setting up your own. Reference:
Spring Boot Security Auto-Configuration
When you include spring-boot-starter-security then the login page will automatically be shown.
To remove this login page-
If you use Maven then removing this dependency and rebuild the project. Already there are some answers for this. Just remove the block (pom.xml):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
If anyone uses Gradle then, just remove the following block from dependencies block(build.gradle) and reload build.gradle:
dependencies {
//implementation 'org.springframework.boot:spring-boot-starter-security'
...
}
If you do not want to change the config file like pom.xml or build.gradle then source code level change will be the best suit for you. To do this, need to update the main class with, change #SpringBootApplication annotation with #SpringBootApplication(exclude = {SecurityAutoConfiguration.class}). This excludes parameter will remove Security configuration.
#SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class SpringCacheApplication {
public static void main(String[] args) {
...
}
...
}
Moreover, if you want to keep the login page, then you can log in with generated security password. You can find it into console, looks like:
Using generated security password: d408ce6f-470d-4**4-950a-81**9651f321
{
"usename" : "user",
"password": "d408ce6f-470d-4**4-950a-81**9651f32"
}
For more information, you can read Spring Security.
You can add a class in your Project,
for Web Security configuration as follows:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/*").permitAll()
.and()
.csrf().disable();
}
}
Check the console to find the password
Also as a username please use "user" as a credential.
If you want to disable that spring functionality, go to your pom xml and delete the dependency below;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
if you really want to disable this login page you may disable your class where is:
public class SecurityConfig extends WebSecurityConfigurerAdapter {
this class is not necessary
in my opinion you haven't create this class whose extends WebSecurityConfigurerAdapter
My code without the starter-security but still ask for login.
Here is the solution:
disable your autoconfiguration in main class,
#SpringBootApplication(exclude= {SecurityAutoConfiguration.class})
If you want the spring security and you've defined the WebSecurityConfig then make sure you have these two annotations on your WebSecurityConfig class:
#Configuration
#EnableWebSecurity
if you have login page displayed; it means that security is activated;
you comment or delete those dependencies from pom.xml:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
or:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
or:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
I had the same issue and in my case it was because of missing #Configuration and #EnableWebSecurity annotations in SecurityConfig file

SpringBoot Application Startup Failed due to autowire JavaMailSender - version 2.0.0-snapshot

I m using Spring Boot 2.0.0.BUILD-SNAPSHOT.
I have a problem when autowiring JavaMailSender or JavaMailSenderImpl.
If i configure #Autowired for JavaMailSender, i m getting below error.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field mailSender in com.hm.assetmanagment.service.MailService required a bean of type 'org.springframework.mail.javamail.JavaMailSenderImpl' that could not be found.
- Bean method 'mailSender' not loaded because #ConditionalOnClass did not find required class 'javax.mail.internet.MimeMessage'
Action:
Consider revisiting the conditions above or defining a bean of type 'org.springframework.mail.javamail.JavaMailSenderImpl' in your configuration.
Below are my pom.xml which has spring boot starter email.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hm.assetmanagement</groupId>
<artifactId>AssetManagementSystem</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AssetManagementSystem</name>
<description>AssetManagementSystem</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</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-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<!-- <exclusions>
<exclusion>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
</exclusion>
</exclusions>-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
package com.hm.assetmanagment.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MailService {
#Autowired
private JavaMailSenderImpl mailSender;
#RequestMapping("/assets/allocateemail/{name}/{email}/{assetid}")
private void sendAssetAllocationEmail(String name, String email, String assetid) {
/*SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(email);
simpleMailMessage.setSubject("Asset Allocation Confirmation");
simpleMailMessage.setText("Hello " + name + "," + assetid + "\n" + " - Asset allocated to you");
mailSender.send(simpleMailMessage);*/
}
}
I tried by adding javax.mail jar/spring context support manually in dependency but it didnt work.
application.properties:
spring.mail.host=smtp.gmail.com
spring.mail.username=xxx#gmail.com
spring.mail.password=xxx
spring.mail.port=587
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.thymeleaf.cache=false
debug=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Main Class:
package com.hm.assetmanagment;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableJpaRepositories
#SpringBootApplication
public class AssetManagementSystemApplication {
public static void main(String[] args) {
SpringApplication.run(AssetManagementSystemApplication.class, "--debug");
//SpringApplication.run(AssetManagementSystemApplication.class, args);
}
}
Please guide.
Update from me Nov22:
If i create new class and enable auto configuration on that class, JavaMailSender and JavaMailSenderImpl are autowired properly and spring boot application starts successfully. Already i have enableautoconfiguration in application.class as well. Is it fine to have two classes configured with enableautoconfiguration? Is there any other way to autowire JavaMailSender?
#EnableAutoConfiguration
public class MailConfig {
#Autowired
private JavaMailSenderImpl mailSender;
}
well it looks like you have not configured the Mailer at all , thus Spring cannot find the bean in order to wire it. If it was a dependency issue , then you would get a ClassNotFoundException or NoClassDefException , which is not your case.
Anyway try to configure your Mailer like this :
#Configuration
public class MailConfig {
#Bean
public JavaMailSender javaMailService() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost("myHost");
javaMailSender.setPort(25);
javaMailSender.setJavaMailProperties(getMailProperties());
return javaMailSender;
}
private Properties getMailProperties() {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.auth", "false");
properties.setProperty("mail.smtp.starttls.enable", "false");
properties.setProperty("mail.debug", "false");
return properties;
}
}
Original answer here
By seeing your code , you need to add below properties to work
Sample app.yml file
spring
mail:
default-encoding: UTF-8
host: localhost
port: 8025
protocol: smtp
test-connection: false
properties.mail.smtp:
starttls.enable: true
Here is the reference
https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/boot-features-email.html
make sure you are reading app properties
Change
#Autowired
private JavaMailSenderImpl mailSender;
to
#Autowired
private JavaMailSender mailSender;
The reason for this is, that by default Spring creates JDK proxies, if a bean class implements an interface. The JDK proxy implements the same interfaces as the bean class, but does not extend the class.

Resources