休息控制器不工作

Raj*_*jat 4 java spring spring-mvc spring-boot

我已经使用 start.spring.io 初始化了 spring boot 项目并添加了 WEB、JPA、H2 依赖项。

Pom文件

<?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>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.10.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>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</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-web</artifactId>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <!-- <scope>runtime</scope> -->
    </dependency>


</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
Run Code Online (Sandbox Code Playgroud)

应用程序属性

spring.h2.console.enabled=true
security.basic.enabled=false
Run Code Online (Sandbox Code Playgroud)

演示应用程序.java

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

用户控制器.java

@RestController
public class UserController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello";
    }
Run Code Online (Sandbox Code Playgroud)

控制台日志

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

2018-02-26 11:24:28.846  INFO 4792 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication on RAJAT-PC with PID 4792 (C:\Users\devra\Downloads\Compressed\demo\target\classes started by rajat in C:\Users\devra\Downloads\Compressed\demo)
2018-02-26 11:24:28.855  INFO 4792 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2018-02-26 11:24:29.018  INFO 4792 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6b67034: startup date [Mon Feb 26 11:24:29 IST 2018]; root of context hierarchy
2018-02-26 11:24:30.894  INFO 4792 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$fa7e8c5a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-02-26 11:24:31.720  INFO 4792 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-02-26 11:24:31.737  INFO 4792 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-02-26 11:24:31.740  INFO 4792 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-02-26 11:24:31.969  INFO 4792 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-02-26 11:24:31.970  INFO 4792 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2957 ms
2018-02-26 11:24:32.307  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-26 11:24:32.308  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-02-26 11:24:32.309  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-02-26 11:24:32.309  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-02-26 11:24:32.310  INFO 4792 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-02-26 11:24:32.311  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-02-26 11:24:32.313  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'webServlet' to [/h2-console/*]
2018-02-26 11:24:33.004  INFO 4792 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-02-26 11:24:33.038  INFO 4792 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2018-02-26 11:24:33.196  INFO 4792 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2018-02-26 11:24:33.199  INFO 4792 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2018-02-26 11:24:33.202  INFO 4792 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2018-02-26 11:24:33.266  INFO 4792 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-02-26 11:24:33.517  INFO 4792 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2018-02-26 11:24:33.807  INFO 4792 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
2018-02-26 11:24:33.816  INFO 4792 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete
2018-02-26 11:24:33.859  INFO 4792 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-02-26 11:24:34.365  INFO 4792 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6b67034: startup date [Mon Feb 26 11:24:29 IST 2018]; root of context hierarchy
2018-02-26 11:24:34.506  INFO 4792 --- [           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)
2018-02-26 11:24:34.508  INFO 4792 --- [           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)
2018-02-26 11:24:34.568  INFO 4792 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:34.569  INFO 4792 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:34.663  INFO 4792 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:35.147  INFO 4792 --- [           main] b.a.s.AuthenticationManagerConfiguration : 

Using default security password: dd5212d7-4de1-4fee-9f6b-f5cd888f2f17

2018-02-26 11:24:35.222  INFO 4792 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2018-02-26 11:24:35.334  INFO 4792 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$ApplicationNoWebSecurityConfigurerAdapter$1@11c713b7, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@2251b3bc, org.springframework.security.web.context.SecurityContextPersistenceFilter@602f8f94, org.springframework.security.web.header.HeaderWriterFilter@2785db06, org.springframework.security.web.csrf.CsrfFilter@603cabc4, org.springframework.security.web.authentication.logout.LogoutFilter@7a9ceddf, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4dfe8b37, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@7e64c1a9, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3fbe503c, org.springframework.security.web.session.SessionManagementFilter@715a70e9, org.springframework.security.web.access.ExceptionTranslationFilter@1cc8416a]
2018-02-26 11:24:35.552  INFO 4792 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-02-26 11:24:35.652  INFO 4792 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-02-26 11:24:35.670  INFO 4792 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 7.302 seconds (JVM running for 7.824)
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,spring 没有映射/hellourl

g00*_*00b 7

考虑到其他答案没有解释为什么它不能按预期工作,这就是原因。

Spring 使用组件扫描来查找符合条件的 bean ( @Repository, @Service, @Component, @Controller, ...)。这通常是通过使用@ComponentScan注释来完成的。这在核心文档中进行了解释:

要自动检测这些类并注册相应的bean,您需要添加@ComponentScan到您的@Configuration类中,其中该basePackages属性是两个类的公共父包。(或者,您可以指定一个逗号/分号/空格分隔的列表,其中包含每个类的父包。)

Spring Boot 默认只扫描主类的同一个包(包括子包)内的组件。这是因为@SpringBootApplication注释@ComponentScan默认包含 a ,如Spring boot 文档中所述

@SpringBootApplication注解相当于使用@Configuration@EnableAutoConfiguration@ComponentScan与他们的默认属性

如果您希望 Spring 自动检测您的控制器,您有三个选择:

  1. 将控制器移至com.example.demo包装中。根据Spring boot 文档,这是推荐的方法。

  2. controller通过添加@ComponentScan注释告诉 Spring 查看包:

    @SpringBootApplication
    @ComponentScan({"com.example.demo", "controller"}) // Add this
    public class DemoApplication {
        // ...
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. controller通过配置以下scanBasePackages属性告诉 Spring 查看包@SpringBootApplication

    @SpringBootApplication(scanBasePackages = {"com.example.demo", "controller"}) // Add this
    public class DemoApplication {
        // ...
    }
    
    Run Code Online (Sandbox Code Playgroud)