为什么SpringBootApplication不将我的控制器注册为处理程序?

时间:2016-04-21 18:05:46

标签: java spring spring-mvc tomcat spring-boot

这是我第一次和春天一起工作,我很难受。这是我到目前为止所拥有的

我在嵌入式tomcat上运行的应用程序

package com.company.project.application;
@SpringBootApplication
public class SampleApplication {
    private static Log logger = LogFactory.getLog(SampleApplication.class);

    @Bean
    protected ServletContextListener listener(){
        return new ServletContextListener() {
            public void contextInitialized(ServletContextEvent servletContextEvent) {
                logger.info("ServletContext initialized ...");
            }

            public void contextDestroyed(ServletContextEvent servletContextEvent) {
                logger.info("ServletContext destroyed ... ");
            }
        };
    }

    public static void main (String[] args){
        SpringApplication.run(SampleApplication.class, args);
    }
}

控制器

package com.company.project.controller;
@Controller
public class PaymentController {
    @RequestMapping("/")
    @ResponseBody
    public String helloWorld(){
        return "hello";
    }
}

我正在使用SampleApplicaiton.main运行此应用程序。我可以在控制台中看到日志等。当我尝试访问http://localhost:8080/时,它会给我404。当我尝试http://localhost:8080/sampleapplicationhttp://localhost:8080/SampleApplication/时,我会收到相同的消息。

我在这里缺少什么?

SpringBoot日志

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.3.RELEASE)

2016-04-21 14:00:54.794  INFO 65461 --- [           main] c.w.p.application.SampleApplication   : Starting SampleApplication on WGs-MacBook-Pro.local with PID 65461 (/Users/username/repos/Sample/target/classes started by username in /Users/username/repos/sample)
2016-04-21 14:00:54.799  INFO 65461 --- [           main] c.w.p.application.SampleApplication   : No active profile set, falling back to default profiles: default
2016-04-21 14:00:54.892  INFO 65461 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1f021e6c: startup date [Thu Apr 21 14:00:54 EDT 2016]; root of context hierarchy
2016-04-21 14:00:55.794  INFO 65461 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2016-04-21 14:00:56.411  INFO 65461 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-04-21 14:00:56.431  INFO 65461 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-04-21 14:00:56.433  INFO 65461 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.32
2016-04-21 14:00:56.569  INFO 65461 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-04-21 14:00:56.569  INFO 65461 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1697 ms
2016-04-21 14:00:56.838  INFO 65461 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2016-04-21 14:00:56.846  INFO 65461 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-04-21 14:00:56.847  INFO 65461 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-04-21 14:00:56.847  INFO 65461 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-04-21 14:00:56.847  INFO 65461 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2016-04-21 14:00:56.879  INFO 65461 --- [ost-startStop-1] c.w.p.application.SampleApplication   : ServletContext initialized ...
2016-04-21 14:00:57.297  INFO 65461 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1f021e6c: startup date [Thu Apr 21 14:00:54 EDT 2016]; root of context hierarchy
2016-04-21 14:00:57.391  INFO 65461 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-04-21 14:00:57.392  INFO 65461 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-04-21 14:00:57.418  INFO 65461 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-04-21 14:00:57.419  INFO 65461 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-04-21 14:00:57.467  INFO 65461 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-04-21 14:00:57.584  INFO 65461 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-04-21 14:00:57.680  INFO 65461 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-04-21 14:00:57.686  INFO 65461 --- [           main] c.w.p.application.SampleApplication   : Started SampleApplication in 3.998 seconds (JVM running for 4.629)
2016-04-21 14:04:49.523  INFO 65461 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-04-21 14:04:49.524  INFO 65461 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-04-21 14:04:49.542  INFO 65461 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 18 ms

1 个答案:

答案 0 :(得分:4)

根据documentation

  

许多Spring Boot开发人员总是对其主类进行注释   使用@Configuration@EnableAutoConfiguration@ComponentScan。   由于这些注释经常被一起使用(特别是如果   你遵循上面的最佳实践),Spring Boot提供了一个   方便的@SpringBootApplication替代方案。

@ComponentScan的默认属性是仅搜索带注释的类的包。

  

如果未定义特定包,则会从中进行扫描   声明此批注的类的包。

在您的情况下,这是SampleApplication,与PaymentController不同。因此,PaymentController不会包含在bean中,也不会包含在处理程序中。

将它们移动到同一个包或添加显式@ComponentScan以同时扫描

package com.company.project.controller;

或者,@SpringBootApplication也可以使用scanBasePackages属性。