休息控制器在春季启动时无效

时间:2017-11-13 10:26:53

标签: java spring spring-boot

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

我可以成功运行我的应用程序而没有错误,但是我写的其余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>
顺便说一下,在我添加一些代码或库(比如德鲁伊)之前,其余的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;
    }
}

它工作正常!

7 个答案:

答案 0 :(得分:1)

我终于明白了。

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

我是多么傻啊!

答案 1 :(得分:0)

创建一个人类来测试:

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

答案 2 :(得分:0)

这里缺少一些东西。首先,您需要将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值之前。

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

美好的一天!

 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 - &gt;本地主机:{端口} /测试

参考文献:

答案 5 :(得分:0)

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

答案 6 :(得分:-1)

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

@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