Java rest控制器在spring boot中不工作

Java rest控制器在spring boot中不工作,java,spring,spring-boot,Java,Spring,Spring Boot,我检查了大多数类似的问题,但没有找到答案。因此我只能发布一个新问题。 我可以成功运行我的应用程序而不出错,但我编写的rest api无法正确访问。我已将我的启动日志与进行了比较,然后发现我没有以下类似的日志: 2017-11-13 17:37:50.921 INFO 6503 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springfram

我检查了大多数类似的问题,但没有找到答案。因此我只能发布一个新问题。

我可以成功运行我的应用程序而不出错,但我编写的rest api无法正确访问。我已将我的启动日志与进行了比较,然后发现我没有以下类似的日志:

2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           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)
2017-11-13 17:37:51.067  INFO 6503 --- [           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)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
控制器文件:

@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
pom.xml文件:

<?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.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.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-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

很好用

尝试应用请求映射注释,如下所述

@RestController
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
  @RequestMapping(path = "/test")
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
此外,请查看以下链接以了解更多示例:
创建要测试的person类:

public class Person{

private String name;
private String nickname;

//getters and setters...
}
在控制器的方法中,尝试以下操作:

 @GetMapping(value ="/test", consumes = {MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<?> helloWorld() {
        Person person = new Person();
        person.setName("test");
        person.setNickname("test2");
        return ResponseEntity.status(HttpStatus.OK).body(person);
    }
@GetMapping(value=“/test”,使用={MediaType.APPLICATION\u JSON\u value})
公共响应helloWorld(){
Person=新人();
person.setName(“测试”);
person.set昵称(“test2”);
返回ResponseEntity.status(HttpStatus.OK).body(person);
}

这里缺少一些东西。首先,需要将RequestMapping添加到定义的函数中,为了返回JSONObject,需要使用@ResponseBody注释和ResponseEntity作为函数的返回类型 示例代码:

@RequestMapping(value = "/testing", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON)
public @ResponseBody ResponseEntity<JSONObject> HelloWorld() {
    JSONObject res = new JSONObject();
    LOGGER.info("HelloWorld Test!");
    res.put("data", "hello world!");
    res.put("errCode", 0);
    return ResponseEntity.status(HttpStatus.OK).body(res);
}
@RequestMapping(value=“/testing”,method=RequestMethod.GET,consumes=MediaType.APPLICATION\u JSON)
public@ResponseBody ResponseEntity HelloWorld(){
JSONObject res=新的JSONObject();
LOGGER.info(“HelloWorld测试!”);
res.put(“数据”,“你好,世界!”);
res.put(“errCode”,0);
返回响应状态(HttpStatus.OK).body(res);
}

@RequestMapping注释既可以用于函数级,也可以用于类级。类级注释值应在最终REST端点中的所有函数@RequestMapping注释值前面加上前缀。

可能是因为它找不到控制器吗?如果是,您可以使用@ComponentScan进行尝试吗@ComponentScan告诉Spring在hello包中查找其他组件、配置和服务,允许它查找控制器

@SpringBootApplication
@ComponentScan(basePackageClasses = TestController.class)
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {
//Your code here
}
你好

 The @RequestMapping annotation should be made in this way

@RestController
public class TestController {

  @RequestMapping(value = "/test", method = RequestMethod.GET)
     public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
但是那样你会得到同样的结果

@RestController
public class TestController {

  @RequestMapping(value = "/test", method = RequestMethod.GET, 
          produces = MediaType.APPLICATION_JSON_VALUE )
    public HashMap HelloWorld() {

         HashMap<String, String> res = new HashMap<String, String>();           
            res.put("data", "hello world");
            res.put("errorCode", "0");
            return res;

    }
}
@RestController
公共类测试控制器{
@RequestMapping(value=“/test”,method=RequestMethod.GET,
products=MediaType.APPLICATION\u JSON\u值)
公共HashMap HelloWorld(){
HashMap res=新的HashMap();
res.put(“数据”,“你好世界”);
res.put(“错误代码”,“0”);
返回res;
}
}
url->localhost:{port}/test

参考资料:


    • 我终于明白了

      我在一个有@PostConstruct注释的方法中写了一个while循环。它必须阻止spring主进程,导致rest控制器没有被加载


      我是多么愚蠢。

      因此,基本上,您的应用程序主方法无法识别控制器、服务、实体等。 首先,请确保您使用的是他们各自的课程。比如控制器类的@Restcontroller

      @RestController
      @service
      @Entity
      @JPARepository
      
      另外,确保您要求spring引导应用程序在不同的包中检查这些类

      @ComponentScan({"com.funky.classes.controller","com.funky.classes.service"})
      @EntityScan("com.funky.classes.model")
      @EnableJpaRepositories("com.funky.classes.repository")
      @SpringBootApplication()... 
      

      这里需要添加什么person类。您可以直接点击url并进行检查。将测试控制器添加到与GreetingController和tryMaybe相同的包中,因为在spring boot web中fastjson和jackson之间存在冲突。请再次删除fastjson依赖项并检查它是否工作正常。@Gurkanyesilyart rest api以前工作正常,当时我使用了fastjsonlibrary@shakeel我已经尝试过了,效果很好,我添加了
      @ComponentScan(basePackageClasses=TestController.class,basePackages=“com.teachermate”)
      ,因为我有其他组件需要注册为bean。但是它不起作用,第二个代码块将不会编译,因为返回类型不同。当使用
      @RestController
      时,将暗示
      @ResponseBody
      @RestController
      @service
      @Entity
      @JPARepository
      
      @ComponentScan({"com.funky.classes.controller","com.funky.classes.service"})
      @EntityScan("com.funky.classes.model")
      @EnableJpaRepositories("com.funky.classes.repository")
      @SpringBootApplication()...