There is a project with 20 controllers approximately. Each controller has its corresponding test class.
When we try to add new controller tests classes, some of the previous tests which were running fine, starts to fail randomly. If any controller test class is annotated with #Ignore, tests get back to normal.
This is the exception thrown by the failing tests:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: org.springframework.web.context.support.GenericWebApplicationContext#22f3fadf has been closed already.
Full log of one failing test:
:: Spring Boot :: (v2.0.3.RELEASE)
2019-07-04T13:01:50,325 INFO [pool-1-thread-17]
o.s.b.StartupInfoLogger: Starting ZipCodeControllerTest on valhala
with PID 17817 (started by wblanck in /home/wblanck/Projects/project)
2019-07-04T13:01:50,325 DEBUG [pool-1-thread-17]
o.s.b.StartupInfoLogger: Running with Spring Boot v2.0.3.RELEASE,
Spring v5.0.7.RELEASE 2019-07-04T13:01:50,325 INFO [pool-1-thread-17]
o.s.b.SpringApplication: No active profile set, falling back to
default profiles: default 2019-07-04T13:01:50,326 INFO
[pool-1-thread-17] o.s.c.s.AbstractApplicationContext: Refreshing
org.springframework.web.context.support.GenericWebApplicationContext#a5a2b92:
startup date [Thu Jul 04 13:01:50 ART 2019]; root of context hierarchy
2019-07-04T13:01:50,448 INFO [pool-1-thread-17]
o.s.b.f.a.AutowiredAnnotationBeanPostProcessor: JSR-330
'javax.inject.Inject' annotation found and supported for autowiring
2019-07-04T13:01:50,772 INFO [pool-1-thread-17]
o.s.w.s.h.AbstractHandlerMethodMapping$MappingRegistry: Mapped
"{[/error]}" onto public
org.springframework.http.ResponseEntity
com.package.controller.WrongPathErrorController.badPathError(javax.servlet.http.HttpServletRequest)
2019-07-04T13:01:50,772 INFO [pool-1-thread-17]
o.s.w.s.h.AbstractHandlerMethodMapping$MappingRegistry: Mapped
"{[/api/users/{device}/zip-code],methods=[GET],produces=[application/json]}"
onto public
org.springframework.http.ResponseEntity
com.package.controller.ZipCodeController.checkZipCode(java.lang.Integer,java.lang.String,java.lang.String,java.lang.Integer,java.lang.String)
... more HandlerMethodMappings ...
2019-07-04T13:01:50,773 INFO [pool-1-thread-17]
o.s.w.s.h.AbstractHandlerMethodMapping$MappingRegistry: Mapped
"{[/swagger-resources/configuration/ui]}" onto public
org.springframework.http.ResponseEntity
springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
2019-07-04T13:01:50,773 INFO [pool-1-thread-17]
o.s.w.s.h.AbstractHandlerMethodMapping$MappingRegistry: Mapped
"{[/swagger-resources]}" onto public
org.springframework.http.ResponseEntity>
springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
2019-07-04T13:01:50,773 INFO [pool-1-thread-17]
o.s.w.s.h.AbstractHandlerMethodMapping$MappingRegistry: Mapped
"{[/swagger-resources/configuration/security]}" onto public
org.springframework.http.ResponseEntity
springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
2019-07-04T13:01:50,824 INFO [pool-1-thread-17]
s.d.s.w.PropertySourcedRequestMappingHandlerMapping: Mapped URL path
[/v2/api-docs] onto method [public
org.springframework.http.ResponseEntity
springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
2019-07-04T13:01:50,859 INFO [pool-1-thread-17]
o.s.w.s.h.AbstractUrlHandlerMapping: Mapped URL path [//favicon.ico]
onto handler of type [class
org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-07-04T13:01:50,913 INFO [pool-1-thread-17]
o.s.w.s.m.m.a.RequestMappingHandlerAdapter: Looking for
#ControllerAdvice:
org.springframework.web.context.support.GenericWebApplicationContext#a5a2b92:
startup date [Thu Jul 04 13:01:50 ART 2019]; root of context hierarchy
2019-07-04T13:01:50,931 INFO [pool-1-thread-17]
o.s.w.s.h.AbstractUrlHandlerMapping: Mapped URL path [/webjars/]
onto handler of type [class
org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-07-04T13:01:50,931 INFO [pool-1-thread-17]
o.s.w.s.h.AbstractUrlHandlerMapping: Mapped URL path [/**] onto
handler of type [class
org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-07-04T13:01:50,938 INFO [pool-1-thread-17]
o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver: Detected
#ExceptionHandler methods in integrationExceptionHandler
2019-07-04T13:01:50,981 INFO [pool-1-thread-17]
o.s.m.w.MockServletContext: Initializing Spring FrameworkServlet ''
2019-07-04T13:01:50,981 INFO [pool-1-thread-17]
o.s.w.s.FrameworkServlet: FrameworkServlet '': initialization started
2019-07-04T13:01:50,987 INFO [pool-1-thread-17]
o.s.w.s.FrameworkServlet: FrameworkServlet '': initialization
completed in 6 ms 2019-07-04T13:01:50,995 INFO [pool-1-thread-17]
o.s.c.s.DefaultLifecycleProcessor$LifecycleGroup: Starting beans in
phase 2147483647 2019-07-04T13:01:50,995 INFO [pool-1-thread-17]
s.d.s.w.p.DocumentationPluginsBootstrapper: Context refreshed
2019-07-04T13:01:50,995 INFO [pool-1-thread-17]
s.d.s.w.p.DocumentationPluginsBootstrapper: Found 1 custom
documentation plugin(s) 2019-07-04T13:01:50,999 INFO
[pool-1-thread-17] s.d.s.w.s.ApiListingReferenceScanner: Scanning for
api listing references 2019-07-04T13:01:51,109 INFO
[pool-1-thread-17] o.s.b.StartupInfoLogger: Started
ZipCodeControllerTest in 0.813 seconds (JVM running for 39.78)
2019-07-04T13:01:51,111 INFO [pool-1-thread-17]
o.s.c.s.AbstractApplicationContext: Closing
org.springframework.web.context.support.GenericWebApplicationContext#40554129:
startup date [Thu Jul 04 13:01:42 ART 2019]; root of context hierarchy
2019-07-04T13:01:51,112 INFO [pool-1-thread-17]
o.s.c.s.DefaultLifecycleProcessor$LifecycleGroup: Stopping beans in
phase 2147483647 Tests run: 3, Failures: 0, Errors: 1, Skipped: 0,
Time elapsed: 14.141 s <<< FAILURE! - in
com.package.controller.ZipCodeControllerTest
testInexistentCheckZipCode(com.package.controller.ZipCodeControllerTest)
Time elapsed: 10.648 s <<< ERROR!
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
java.lang.IllegalStateException:
org.springframework.web.context.support.GenericWebApplicationContext#22f3fadf
has been closed already at
com.package.controller.ZipCodeControllerTest.testInexistentCheckZipCode(ZipCodeControllerTest.java:80)
Caused by: java.lang.IllegalStateException:
org.springframework.web.context.support.GenericWebApplicationContext#22f3fadf
has been closed already at
com.package.controller.ZipCodeControllerTest.testInexistentCheckZipCode(ZipCodeControllerTest.java:80)
Tests are very similar, basically the common structure is:
#RunWith(SpringRunner.class)
#WebMvcTest(Controller.class)
public class ControllerTest {
private static final String URL_TEMPLATE = ".....";
#Autowired
private MockMvc mvc;
#Autowired
private ObjectMapper mapper;
#MockBean
private Service service;
private CustomParams params;
private CustomRequest request;
#Before
public void init() {
// initialize params and request ...
}
#Test
public void methodOk() throws Exception {
when(service.method(refEq(params))).thenReturn(RESPONSE);
mvc.perform(MockMvcRequestBuilders.post(URL_TEMPLATE)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(mapper.writeValueAsString(request)))
.andExpect(status().isOk())
.andExpect(jsonPath(STATUS_MESSAGE_PATH, is(MESSAGE_CODE_OK)))
.andExpect(jsonPath(STATUS_CODE_PATH, is(STATUS_OK.getStatusCode()))));
}
#Test
public void badRequest() throws Exception {
mvc.perform(MockMvcRequestBuilders.post(URL_TEMPLATE))
.andExpect(status().isBadRequest())
.andExpect(jsonPath(ERROR_MESSAGE_PATH).isNotEmpty());
}
Controllers have a structure like the following:
#RestController
public class Controller {
private Service service;
#PostMapping(value = "/api/some-url", produces = {"application/json"})
public ResponseEntity<CustomResponse> method(
#RequestHeader("someheaders") Integer someHeaders,
#RequestBody CustomRequest someBody) {
CustomParams params = new CustomParams();
params.setApplicationType(applicationType);
params.someHeaders(someHeaders);
return service.method(params);
}
I can't understand the reason of the exceptions and the fact that they occur in different tests in each run.
I've changed classes and variable's names due to confidentiality.
You should use DirtiesContext annotation on your tests. This will assure you'll get clean context on each test and they will not not interfere with eachother
Related
I have a spring boot project as producer which have API endpoints, created via RouterFunction.
That API endpoint call handler which call a service and then make a call to JPA repository.
We have used liquibase to create db tables and for writing testcases we have used postgressql testcontainer.
I have written base class for producer as below:
#SpringBootTest
public abstract class RestBase extends TestBase {
#Autowired
private AccountHandler accountHandler;
#BeforeEach
public void setup() {
RestAssuredWebTestClient.webTestClient(WebTestClient.bindToRouterFunction(
new RouterConfig(accountHandler).routes()).build());
}
}
However, when I am trying to run mvn clean install, below stack trace is coming.
[INFO] Running com.example.RestTest
2021-09-02 13:46:26.207 INFO 25420 --- [ main] .b.t.c.SpringBootTestContextBootstrapper : Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.example.RestTest], using SpringBootContextLoader
2021-09-02 13:46:26.208 INFO 25420 --- [ main] o.s.t.c.support.AbstractContextLoader : Could not detect default resource locations for test class [com.example.RestTest]: no resource found for suffixes {-context.xml, Context.groovy}.
2021-09-02 13:46:26.208 INFO 25420 --- [ main] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [com.example.RestTest]: RestTest does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.127 s <<< FAILURE! - in com.example.RestTest
[ERROR] com.example.RestTest Time elapsed: 0.127 s <<< ERROR!
java.lang.IllegalStateException: Unable to find a #SpringBootConfiguration, you need to use #ContextConfiguration or #SpringBootTest(classes=...) with your test
2021-09-02 13:46:26.346 INFO 25420 --- [ main] c.e.e.c.ContainerEnvironmentResource : Stopping all test containers.
2021-09-02 13:46:26.778 INFO 25420 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-09-02 13:46:26.781 INFO 25420 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-09-02 13:46:26.795 INFO 25420 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] RestTest » IllegalState Unable to find a #SpringBootConfiguration, you need to...
How to solve this issue? Is there any issue with my base test class?
Router Config class looks like below:
#Configuration
#RequiredArgsConstructor
public class RouterConfig {
private final AccountHandler accountHandler;
#Bean
public RouterFunction<ServerResponse> routes (){
return route()
.GET("/accounts",accountHandler::retrieveAccountByFilter)
.build();
}
}
I mean literally it is said right there in the error message what you should do. Just provide the configuration class in #SpringBootTest annotation. Also for contract tests you should not start any databases or repositories. You should mock them out.
Make sure that the classes you are testing are in the same namespace as your #SpringBootApplication class, or are in namespaces UNDER the namespace that contains your #SpringBootApplication class.
For example, if your app class is in com.example.demo.MyApplication but the classes you are testing is com.example.MyClass S
Or if they need to be in separate namespace trees, you may try adding the list of app classes to your #SpringBootTest annotation, e.g.
#SpringBootTest(classes=YouAppClassName.class)
public abstract class RestBase extends TestBase {
...
}
this is strange but my spring boot api taking much longer that expected when deployed on aws lambda.
in the cloudwatch log, i see spring boot is starting up twice first with default profile and second with a profile i set.
Why should it boot twice.. that is significantly costing time..
Source Code:
lambdahandler.java
public class LambdaHandler implements RequestStreamHandler {
private static SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;
static {
try {
handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class);
handler.activateSpringProfiles("lambda");
} catch (ContainerInitializationException e) {
// Re-throw the exception to force another cold start
e.printStackTrace();
throw new RuntimeException("Could not initialize Spring Boot application", e);
}
}
application.java
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
both these files are in the same package
config.java
#Configuration
#EnableWebMvc
#Profile("lambda")
public class Config {
/**
* Create required HandlerMapping, to avoid several default HandlerMapping instances being created
*/
#Bean
public HandlerMapping handlerMapping() {
return new RequestMappingHandlerMapping();
}
/**
* Create required HandlerAdapter, to avoid several default HandlerAdapter instances being created
*/
#Bean
public HandlerAdapter handlerAdapter() {
return new RequestMappingHandlerAdapter();
}
..
..
}
pom.xml
<dependency>
<groupId>com.amazonaws.serverless</groupId>
<artifactId>aws-serverless-java-container-spring</artifactId>
<version>[0.1,)</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>3.1.0</version>
</dependency>
cloudwatch log
07:16:51.546 [main] INFO com.amazonaws.serverless.proxy.internal.LambdaContainerHandler - Starting Lambda Container Handler
:: Spring Boot ::
2020-09-05 07:16:52.724 INFO 1 --- [ main] lambdainternal.LambdaRTEntry : Starting LambdaRTEntry on 169.254.184.173 with PID 1 (/var/runtime/lib/LambdaJavaRTEntry-1.0.jar started by sbx_user1051 in /)
2020-09-05 07:16:52.726 INFO 1 --- [ main] lambdainternal.LambdaRTEntry : No active profile set, falling back to default profiles: default
2020-09-05 07:16:52.906 INFO 1 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#1e81f4dc: startup date [Sat Sep 05 07:16:52 UTC 2020]; root of context hierarchy
..
..
2020-09-05 07:16:57.222 INFO 1 --- [ main] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 40 ms
:: Spring Boot ::
2020-09-05 07:16:57.442 INFO 1 --- [ main] lambdainternal.LambdaRTEntry : Starting LambdaRTEntry on 169.254.184.173 with PID 1 (/var/runtime/lib/LambdaJavaRTEntry-1.0.jar started by sbx_user1051 in /)
2020-09-05 07:16:57.442 INFO 1 --- [ main] lambdainternal.LambdaRTEntry : The following profiles are active: lambda
2020-09-05 07:16:57.445 INFO 1 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5ef60048: startup date [Sat Sep 05 07:16:57 UTC 2020]; root of context hierarchy
Why should it boot twice ?
I suspect your code change with activateSpringProfiles force reinitialisation.
handler.activateSpringProfiles("lambda");
https://github.com/awslabs/aws-serverless-java-container/blob/master/aws-serverless-java-container-spring/src/main/java/com/amazonaws/serverless/proxy/spring/SpringBootLambdaContainerHandler.java#L149
Try setting active profile with env variable SPRING_PROFILES_ACTIVE as part of lambda configuration file.
Java and serverless
If you use java for serverless application like AWS lambdas I would recommend for looking a framework which supports Ahead-of-Time compilation which will boost a lot your application start.
For instance have a look at Micronaut, Quarkus using with Graalvm.
Spring Boot is not the best option using with directly with AWS lambdas.
I already add #SpringBootTest in all testcase.
'Run all test' in IDEA is OK, but when I use Maven test it didn't work.
how to reuse context in Maven test commend.
has any friend meet this problem? thx!
my test case like this:
#SpringBootTest
class EventControllerTest extends BaseTester{
...
}
#RunWith(SpringRunner::class)
#SpringBootTest
class BaseTester{}
maven log:
2018-07-04 16:09:38.766 INFO [-,,,] 12601 --- [ Thread-9] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#2577d6c8: startup date [Wed Jul 04 16:09:29 CST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#54eb2b70
2018-07-04 16:09:38.792 INFO [-,,,] 12601 --- [ Thread-9] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
Running com.fintend.ctc.controller.InviteControllerTest
16:09:40.535 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.fintend.ctc.controller.InviteControllerTest]
16:09:40.541 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
16:09:40.549 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
16:09:40.570 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test c
I have used STS and now I am using IntelliJ Ultimate Edition but I am still getting the same output. My controller is not getting mapped thus showing 404 error. I am completely new to Spring Framework.
DemoApplication.java
package com.webservice.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
HelloController.java
package com.webservice.demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HelloController {
#RequestMapping("/hello")
public String sayHello(){
return "Hey";
}
}
Console Output
com.webservice.demo.DemoApplication : Starting DemoApplication on XFT000159365001 with PID 11708 (started by Mayank Khursija in C:\Users\Mayank Khursija\IdeaProjects\demo)
2017-07-19 12:59:46.150 INFO 11708 --- [ main] com.webservice.demo.DemoApplication : No active profile set, falling back to default profiles: default
2017-07-19 12:59:46.218 INFO 11708 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#238e3f: startup date [Wed Jul 19 12:59:46 IST 2017]; root of context hierarchy
2017-07-19 12:59:47.821 INFO 11708 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8211 (http)
2017-07-19 12:59:47.832 INFO 11708 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-07-19 12:59:47.832 INFO 11708 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15
2017-07-19 12:59:47.944 INFO 11708 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-07-19 12:59:47.944 INFO 11708 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1728 ms
2017-07-19 12:59:47.987 INFO 11708 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-07-19 12:59:48.510 INFO 11708 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-07-19 12:59:48.519 INFO 11708 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2017-07-19 12:59:48.634 INFO 11708 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8211 (http)
2017-07-19 12:59:48.638 INFO 11708 --- [ main] com.webservice.demo.DemoApplication : Started DemoApplication in 2.869 seconds (JVM running for 3.44)
I too had the similar issue and was able to finally resolve it by correcting the source package structure following this
Your Controller classes are not scanned by the Component scanning. Your Controller classes must be nested below in package hierarchy to the main SpringApplication class having the main() method, then only it will be scanned and you should also see the RequestMappings listed in the console output while Spring Boot is getting started.
Tested on Spring Boot 1.5.8.RELEASE
But in case you prefer to use your own packaging structure, you can always use the #ComponentScan annotation to define your basePackages to scan.
Because of DemoApplication.class and HelloController.class in the same package
Locate your main application class in a root package above other classes
Take look at Spring Boot documentation Locating the Main Application Class
Using a root package also allows component scan to apply only on your
project.
For example, in your case it looks like below:
com.webservice.demo.DemoApplication
com.webservice.demo.controller.HelloController
In my case, it was missing the dependency from pom.xml, otherwise everything compiled just fine. The 404 and missing mappings info from Spring logs were the only hints.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
I also had trouble with a similar issue and resolved it using the correct package structure as per below. After correction, it is working properly.
e.g.
Spring Application Main Class is in package com.example
Controller Classes are in package com.example.controller
Adding #ComponentScan(com.webservice) in main class above #SpringBootApplication will resolve your problem. Refer below code
package com.webservice.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#ComponentScan(com.webservice)
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
In my case, I was using #Controller instead of #RestController with #RequestMapping
In my opinion, this visibility problem comes when we leave the component scan to Spring which has a particular way of looking for the classes using standard convention.
In this scenario as the Starter class(DemoApplication)is in com.webservice.demo package, putting Controller one level below will help Spring to find the classes using the default component scan mechanism. Putting HelloController under com.webservice.demo.controller should solve the issue.
It depends on a couple of properties:
server.contextPath property in application properties. If it's set to any value then you need to append that in your request url. If there is no such property then add this line in application.properties server.contextPath=/
method property in #RequestMapping, there does not seem to be any value and hence, as per documentation, it should map to all the methods. However, if you want it to listen to any particular method then you can set it to let's say method = HttpMethod.GET
I found the answer to this. This was occurring because of security configuration which is updated in newer versions of Spring Framework. So i just changed my version from 1.5.4 to 1.3.2
In my case I used wrong port for test request - Tomcat was started with several ones exposed (including one for monitoring /actuator).
In my case I changed the package of configuration file. Moved it back to the original com.example.demo package and things started working.
Another case might be that you accidentally put a Java class in a Kotlin sources directory as I did.
Wrong:
src/main
┕ kotlin ← this is wrong for Java
┕ com
┕ example
┕ web
┕ Controller.class
Correct:
src/main
┕ java ← changed 'kotlin' to 'java'
┕ com
┕ example
┕ web
┕ Controller.class
Because when in Kotlin sources directory, Java class won't get picked up.
All other packages should be an extension of parent package then only spring boot app will scan them by default.
Other option will be to use #ComponentScan(com.webservice)
package structure
👋 I set up 🍃Spring Boot Security in Maven deps. And it automatically deny access to unlogged users also for login page if you haven't change rules for it.
So I prefered my own security system and deleted this dependency.🤓
If you want to use Spring Security. You can wrote WebSecurityConfig like this:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserService userService;
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf()
.disable()
.authorizeRequests()
//Доступ только для не зарегистрированных пользователей
.antMatchers("/registration").not().fullyAuthenticated()
//Доступ только для пользователей с ролью Администратор
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/news").hasRole("USER")
//Доступ разрешен всем пользователей
.antMatchers("/", "/resources/**").permitAll()
//Все остальные страницы требуют аутентификации
.anyRequest().authenticated()
.and()
//Настройка для входа в систему
.formLogin()
.loginPage("/login")
//Перенарпавление на главную страницу после успешного входа
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/");
}
#Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder());
}
}
from [https://habr.com/ru/post/482552/] (in russian)
I use gradle as build tool for a spring boot application and there I am confronted with some strange behavior. Gradle shows more logging-information on explicitly turn test-outputs off as if I do not specify anything at all.
This is quite strange, because a explicit disable-statement should be at least as expressive as no configuration, or shouldn't it?
Example:
If I add the following lines to my build.gradle, I get a by far more verbose logging output on running gradle test:
test{
testLogging {
showStackTraces = false
showStandardStreams = false
showExceptions = false
showCauses = false
events "failed"
exceptionFormat "short"
}
}
EDIT:
I changed it to events = [] as #Peter_Niederwieser suggested. Now nearly all messages disappear, except the following one. Has somebody or other an idea how I can suppress them all? I only want to show the result 34 tests completedand maybe a link to the report.
:backend:test
Download http://repo1.maven.org/maven2/org/jacoco/org.jacoco.agent/0.6.2.201302030002/org.jacoco.agent-0.6.2.201302030002.pom
Download http://repo1.maven.org/maven2/org/jacoco/org.jacoco.build/0.6.2.201302030002/org.jacoco.build-0.6.2.201302030002.pom
Download http://repo1.maven.org/maven2/org/jacoco/org.jacoco.agent/0.6.2.201302030002/org.jacoco.agent-0.6.2.201302030002.jar
objc[1360]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.7.0_65.jdk/Contents/Home/bin/java and /Library/Java/JavaVirtualMachines/jdk1.7.0_65.jdk/Contents/Home/jre/lib/libinstrument.dylib. One of the two will be used. Which one is undefined.
08:50:37.135 [Thread-7] INFO o.s.c.s.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext#228186d4: startup date [Sat Dec 06 08:50:35 CET 2014]; root of context hierarchy
08:50:37.135 [Thread-6] INFO o.s.c.s.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext#4d18a206: startup date [Sat Dec 06 08:50:35 CET 2014]; root of context hierarchy
08:50:37.135 [Thread-5] INFO o.s.c.s.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext#5221dfe5: startup date [Sat Dec 06 08:50:35 CET 2014]; root of context hierarchy
08:50:37.135 [Thread-8] INFO o.s.w.c.s.GenericWebApplicationContext - Closing org.springframework.web.context.support.GenericWebApplicationContext#5a5fbef7: startup date [Sat Dec 06 08:50:36 CET 2014]; root of context hierarchy
08:50:37.166 [Thread-7] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
08:50:37.166 [Thread-6] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
08:50:37.167 [Thread-5] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
08:50:37.167 [Thread-8] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
08:50:37.167 [Thread-7] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#65bad9fe: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,testConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor]; root of factory hierarchy
08:50:37.168 [Thread-6] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#c355f75: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,testConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor]; root of factory hierarchy
08:50:37.168 [Thread-5] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#6dd79791: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,testConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor]; root of factory hierarchy
08:50:37.168 [Thread-8] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#75a5ec9: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.co ntext.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,testConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor]; root of factory hierarchy
08:50:37.175 [Thread-7] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'testConfig'
08:50:37.175 [Thread-6] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'testConfig'
08:50:37.176 [Thread-5] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'testConfig'
08:50:37.176 [Thread-8] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'testConfig'
34 tests completed, 9 failed
:backend:test FAILED
The default is events = []. The code above sets events "failed", which will result in more verbose logging (each failed test will be logged individually).