java Spring Boot 中的支架控制器不工作

7vux5j2d  于 2023-01-04  发布在  Java
关注(0)|答案(8)|浏览(110)
    • 我已经检查了大多数类似的问题,没有找到答案。所以我只能发布一个新问题。**

我可以成功地运行我的应用程序,没有错误,但我写的rest api不能正确访问.我比较了我的启动日志与official tutorials,然后我发现我没有类似的日志如下:

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

控制器文件:

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

顺便说一句,在我添加一些代码或库(如Druid)之前,其余的api工作正常。但我不知道是什么原因造成的,有人能帮助我吗?或者有人能告诉我调试它的方法吗?谢谢!
如果你需要任何其他信息,请在评论中告诉我。

    • 更新**

我已经将official tutorials中的控制器修改为

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

它工作正常!

hiz5n14c

hiz5n14c1#

我终于想通了。
我在一个有@PostConstruct注解的方法中写了一个while循环。它必须阻塞spring主进程,导致rest控制器无法加载。
我真傻。

laik7k3q

laik7k3q2#

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

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

kmpatx3s3#

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

@RestController
@service
@Entity
@JPARepository

另外,请确保您正在请求spring Boot 应用程序检查不同包中的这些类

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

swvgeqrz4#

创建要测试的人员类:

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

kuhbmx9i5#

这里有几点遗漏。首先,您需要将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可以在函数级别和类级别上使用。类级别Annotation值应该在最终REST端点中的所有函数@RequestMapping Annotation值之前。

kqqjbcuj

kqqjbcuj6#

日安!

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-〉本地主机:{端口}/test
参考文献:

  • http://spring.io/guides/tutorials/bookmarks/#_getting_started
  • https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-first-application-code
am46iovg

am46iovg7#

我在Springboot 3.0.1中遇到了同样的问题,尤其是使用Tomcat 10.14的版本。您必须在Springboot应用程序类中使用此格式,否则将抛出白色标签页面。
这是要尝试的格式。2打开springboot类应用程序

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

goqiplq28#

尝试应用请求Map注解,如下所述。

@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

相关问题