繁体   English   中英

rest controller 在 spring 引导中不工作

[英]rest controller not working in 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.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]

这是我的一些 java 文件,希望任何人都能找到一些关键点来解决我的问题

主应用文件:

package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

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

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}

controller 文件:

@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>

顺便说一句,在我添加一些代码或库(如德鲁伊)之前, rest api 工作正常。 但我不知道是什么原因造成的,有人可以帮忙吗? 或者任何人都可以告诉我调试它的方法吗? 谢谢!

如果您需要任何其他信息,请在评论中告诉我。


更新

我把官方教程中的controller修改为

@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

它工作正常!

我终于弄明白了。

我在一个带有@PostConstruct Annotation的方法中写了一个while循环。它必须阻塞spring主进程,导致其余的控制器没有被加载。

我是多么愚蠢。

创建一个人类来测试:

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);
    }

这里缺少一些东西。 首先,您需要将RequestMapping添加到已定义的函数并返回JSONObject,您需要使用@ResponseBody Annotation以及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 Annotation既可用于功能级别,也可用于类级别。 类级别注释值应该在最终REST端点中的所有函数@RequestMapping Annotation值之前。

可能是因为它无法找到控制器吗? 如果是,您可以尝试使用@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;

    }
}

url - > localhost:{port} / test

参考文献:

因此,基本上您的应用程序主要方法无法识别控制器,服务,实体等。首先请确保您使用的是各自的类。 就像控制器类的@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()... 

我在 springboot 3.0.1 上遇到了同样的问题,尤其是那些使用 tomcat 10.14 的问题。 您将必须在您的 springboot 应用程序 class 上使用此格式,否则它将抛出白色 label 页面。

这是要尝试的格式。 放上springboot class应用

@EnableAutoConfiguration
@SpringBootApplication
@AutoConfigurationPackage
@ComponentScan(basePackageClasses = {UserResourceController.class, UserService.class, Repo.class})
public class DemoApplication {
    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);
    }
}

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

@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;
    }
}

另外,请查看以下链接以获取更多示例: http//www.baeldung.com/spring-requestmapping

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM