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)
Related
Let me start by saying I am currently getting this error when trying to load my Spring Boot app:
2022-07-04 15:26:03.640 DEBUG 15484 --- [nio-8881-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.gtt.gcaas.console.controller.ConsoleController#greeting()
2022-07-04 15:26:03.655 DEBUG 15484 --- [nio-8881-exec-1] o.s.web.servlet.DispatcherServlet : Failed to complete request: javax.servlet.ServletException: Could not resolve view with name 'welcome' in servlet with name 'dispatcherServlet'
2022-07-04 15:26:03.665 ERROR 15484 --- [nio-8881-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Could not resolve view with name 'welcome' in servlet with name 'dispatcherServlet'] with root cause
javax.servlet.ServletException: Could not resolve view with name 'welcome' in servlet with name 'dispatcherServlet'
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1380) ~[spring-webmvc-5.3.20.jar:5.3.20]
My Spring Main class is:
#SpringBootApplication
#ComponentScan(basePackages = {"com.gtt.gcaas.console.controller", "com.gtt.gcaas.device.details", "com.gtt.gcaas.device.root", "com.gtt.gcaas.device.db", "com.gtt.gcaas.device.db.service"})
#ConfigurationPropertiesScan(basePackages = {"com.gtt.gcaas.device.configuration"})
#EnableJpaRepositories(basePackages = {"com.gtt.gcaas.device.db.repository"})
#EnableWebMvc
#EntityScan(basePackages = {"com.gtt.gcaas.device.db.jpa"})
public class NcaasDeviceConnectionApplication {
public static void main(String[] args) {
SpringApplication.run(NcaasDeviceConnectionApplication.class, args);
}
}
My Controller Class is:
package com.gtt.gcaas.console.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class ConsoleController {
#GetMapping("/greeting")
public String greeting() {
return "welcome";
}
}
I have declared this in my application.properties along with a few other hibernate properties:
logging.level.ch.qos.logback==DEBUG
spring.devtools.restart.enabled=true
debug=true
logging.file.path=C:/logs
spring.mvc.view.prefix=/WEB-INF/html/
spring.mvc.view.suffix=.html
But when I hit the URL http://localhost:8080/greeting I get the above error mentioned. First I tried with JAR packaging, but then switched to WAR, but the outcome is the same.
My folder structure is:
Any help on this would be nice. Thanks in advance.
Just put your welcome.html to /src/main/resources/WEB-INF/html/ and add the following properties to the application.properties :
spring.mvc.view.suffix=.html
spring.web.resources.static-locations=classpath:/WEB-INF/html
Usually there's not need to set the static resource locations, since there are some predefined/well-known ones:
By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext.
(https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#web.servlet.spring-mvc.static-content)
I.e. if you put your static resources in any of those directories under src/main/resources Spring will see them.
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 have an example project here. In this multi module project. I have module promotion-service on which the PromotionConfiguration relies on other configurations to be completed first.
#Configuration
#AutoConfigureAfter({RulesConfiguration.class, PointsConfiguration.class})
public class PromotionConfiguration
{
#Bean
public PromotionService promotionService(ObjectProvider<List<Rule>> rules)
{
System.out.println("Adding PromotionService to context");
List<Rule> ruleList = rules.getIfAvailable();
if (!ruleList.isEmpty())
{
ruleList.sort(Comparator.comparingInt(Rule::getOrder));
}
return new PromotionServiceImpl(ruleList);
}
}
But when the spring boot application that has a dependency of module promotion-service the rules are added to the context after the promotion-service is
2018-02-18 11:20:26.743 INFO 11582 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
Adding PromotionService to context
Adding PointRule to context.
Adding PromotionRule to context.
2018-02-18 11:20:27.087 INFO 11582 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#196a42c3: startup date [Sun Feb 18 11:20:25 EST 2018]; root of context hierarchy
There is a difference between parsing the configuration and its structure and effectively creating beans at runtime. What is the concrete problem here?
If I run your project, the promotionService is created with 2 rules as you'd expect. If I add #ConditionalOnMissingBean(Rule.class) on promotionService it is not created (which proves the context knows that at least one Rule bean is going to be created).
You shouldn't worry too much about the runtime part, the context is free to invoke the necessary factory methods (i.e. #Bean annotated methods) according to its optimized plan (it namely does smart stuff to resolve cycles).
The reason why you get this log output is that you're not asking the context to resolve the Rule beans. ObjectProvider is a proxy that won't do anything until you ask for something (getAvailable in this case).
I've changed the injection point to use List<Rule> and I got the following:
Adding PointRule to context.
Adding PromotionRule to context.
Adding PromotionService to context
So all is good. But please, rename your auto-configuration so that they ends with AutoConfiguration rather than Configuration.
1.When using #ServerEndpoint, Junit does not work,the websocket config as list,when #ServerEndpoint is commend out, junit works well
#ServerEndpoint(value = "/websocket", configurator = SessionForWebSocket.class)
#Component
public class WebSocketBean {
....
}
2. myjunit config is
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes = HdConsumerApplication.class)
#WebAppConfiguration
#Transactional
public class HdJunitTest {}
3.when run junit,i got the error:
2017-08-18 21:47:17 INFO [main] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/env || /env.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-08-18 21:47:17 INFO [main] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/actuator || /actuator.json],produces=[application/json]}" onto public org.springframework.hateoas.ResourceSupport org.springframework.boot.actuate.endpoint.mvc.HalJsonMvcEndpoint.links()
2017-08-18 21:47:17 INFO [main] org.springframework.web.socket.server.standard.ServerEndpointExporter - Registering #ServerEndpoint class: class net.huadong.tech.msg.WebSocketBean
2017-08-18 21:47:17 INFO [main] org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer -
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-08-18 21:47:17 ERROR [main] org.springframework.boot.SpringApplication - Application startup failed
java.lang.UnsupportedOperationException: MockServerContainer does not support addEndpoint(Class)
at org.springframework.test.context.web.socket.MockServerContainer.addEndpoint(MockServerContainer.java:126)
at org.springframework.web.socket.server.standard.ServerEndpointExporter.registerEndpoint(ServerEndpointExporter.java:145)
at org.springframework.web.socket.server.standard.ServerEndpointExporter.registerEndpoints(ServerEndpointExporter.java:129)`enter code here`
at org.springframework.web.socket.server.standard.ServerEndpointExporter.afterSingletonsInstantiated(ServerEndpointExporter.java:107)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:779)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
4.is anymethod can help me,fix the matter ,or when junit exclude WebSocketBean
I had the same problem, but when I added the following code it solved the problem. Hope it helps you.
#RunWith(SpringRunner.class)
#SpringBootTest(classes = ZplanApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
I have an Environment Variable on an Ubuntu server, SDB_DOMAIN, that I'm trying to pass to this gradle properties file:
https://github.com/Netflix/SimianArmy/blob/master/src/main/resources/janitor.properties#L20
What's the syntax to pull environment variables into a properties file like this? I've tried a couple different ways, one example being: simianarmy.janitor.snapshots.ownerId = System.getenv("SIMIAN_OWNER_ID") but that just returns the literal value when I start the jetty server withgradlew jettRun and watch the logs.
19:55:53.957 [main] INFO c.n.s.basic.BasicSimianArmyContext - using standard class for simianarmy.client.recorder.class
19:55:54.060 [main] INFO c.n.simianarmy.aws.SimpleDBRecorder - Creating SimpleDB domain: "System.getenv(SDB_DOMAIN)"
19:55:54.122 [main] WARN c.n.simianarmy.aws.SimpleDBRecorder - Error while trying to auto-create SimpleDB domain
com.amazonaws.services.simpledb.model.InvalidParameterValueException: Value ("System.getenv(SDB_DOMAIN)") for parameter DomainName is invalid. (Service: AmazonSimpleDB; Status Code: 400; Error Code: InvalidParameterValue; Request ID: 4aabdeb2-68a5-0f49-dacd-17c96f375793)
Here is what I did. I Wanted my Spring-Boot Application to show me $HOME variable.
My application.properties file:
variable.home = #{ systemEnvironment['HOME'] }
Class that is using it:
#Component
public class SomeName implements CommandLineRunner {
#Value("${variable.home}" )
String home;
#Override
public void run(String... args) throws Exception {
System.out.println(home);
}
public String getHome() {
return home;
}
public void setHome(String home) {
this.home = home;
}
}
Spring boot starting log:
2015-12-10 17:46:07.622 INFO 5710 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2015-12-10 17:46:07.652 INFO 5710 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
/home/dogbert
2015-12-10 17:46:07.655 INFO 5710 --- [ main] com.example.DemoApplication : Started DemoApplication in 1.431 seconds (JVM running for 1.614)
and echo $HOME:
dogbert#borsuk:~$ echo $HOME
/home/dogbert
dogbert#borsuk:~$
I hope this helps.