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

Em *_* Ae 2 java spring tomcat spring-mvc spring-boot

这是我第一次使用 spring,我有点卡住了。这是我到目前为止所拥有的

我在嵌入式 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器

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

我正在使用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
Run Code Online (Sandbox Code Playgroud)

Sav*_*ior 5

根据文档

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

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

如果没有定义特定的包,将从声明该注解的类的包开始扫描。

在您的情况下,即SampleApplication,它与PaymentController. PaymentController因此不会作为 bean 或处理程序包含在内。

要么将它们移动到同一个包中,要么添加一个显式@ComponentScan来也扫描

package com.company.project.controller;
Run Code Online (Sandbox Code Playgroud)

或者,@SpringBootApplication也有一个scanBasePackages可以使用的属性。