SpringBoot RequestMapping方法未调用

时间:2018-11-26 20:27:47

标签: java spring spring-boot

我正在学习SpringBoot。使用Spring JavaPersistenceAPI(JPA)和apache derby作为数据库。 我无法将URL映射到方法上

我有主题:

@Entity
public class Topic {

@Id
private String id;
private String name;
private String description;

public Topic() {

}

public Topic(String id, String name, String description) {
    this.id = id;
    this.name = name;
    this.description = description;
} ... getters & setters...

我有一个Topic控制器。效果很好:

@RestController
    public class TopicController {

@Autowired
private TopicService topicServ;

@RequestMapping("/topics")
public List<Topic> getAllTopics() {
    return topicServ.getAllTopics();
} 
@RequestMapping("/topics/{topicId}")
public Topic getTopic(@PathVariable String topicId) {
    return topicServ.getTopic(topicId);
}... more methods (they work fine)

每个主题都有课程:

@Entity
public class Course {

private String id;
private String name;
private String description;
@ManyToOne
private Topic topic;

public Course() {

}

public Course(String id, String name, String description, String topicId) {
    this.id = id;
    this.name = name;
    this.description = description;
    this.setTopic(new Topic(topicId, "CourseConstructorNAME", "CourseConstructorDESCRIPTION"));
} ... getters & setters ...

我有课程控制器,可以在其中找到问题

@RestController
public class CourseController {

@Autowired
private CourseService courseServ;

@GetMapping(value = "/topics/{topicId}/courses")
public List<Course> getAllCourses(@PathVariable("topicId") String topicId){
    System.out.println("Hi"); *<-- does not print anything*
    return courseServ.getAllCourses(topicId);
}

问题在于,向http://localhost:8080/topics/java/courses发出GET请求,返回404错误消息:

{
"timestamp": "2018-11-26T19:30:08.871+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/topics/java/courses"
}

我希望获得与从URL提取的主题ID对应的课程列表。该失败使我感到困惑,因为主题控制器可以正常工作并且几乎相同。

因此,由于我放在上方的系统输出不输出任何内容,因此我必须做的事情确实很愚蠢;但以防万一,这是CourseServ的代码:

@Service
public class CourseService {

@Autowired
private CourseRepository courseRepo;

public List<Course> getAllCourses(String topicId){
    System.out.println("Calling get all courses from course service");
    List<Course> theList = new ArrayList<Course>();
    courseRepo.findByTopic_Id(topicId).forEach(theList::add);

    System.out.println(theList.toString());

    return theList; 
}

这是CourseRepo:

public interface CourseRepository extends CrudRepository<Course, String> {

    public List<Course> findByTopic_Id(String topicId);
}

这是Spring控制台日志:

2018-11-26 13:29:25.142  INFO 16252 --- [           main] P.ProjectNameWithJpaApplication          : Starting ProjectNameWithJpaApplication on JulioPHX with PID 16252 (C:\SpringToolSuite\workspace\ProjectNameWithJPA\target\classes started by JulioPHX in C:\SpringToolSuite\workspace\ProjectNameWithJPA)
2018-11-26 13:29:25.148  INFO 16252 --- [           main] P.ProjectNameWithJpaApplication          : No active profile set, falling back to default profiles: default
2018-11-26 13:29:27.107  INFO 16252 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2018-11-26 13:29:27.238  INFO 16252 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 116ms. Found 1 repository interfaces.
2018-11-26 13:29:28.254  INFO 16252 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c18d73e6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-11-26 13:29:29.466  INFO 16252 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-11-26 13:29:29.501  INFO 16252 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-11-26 13:29:29.502  INFO 16252 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/9.0.12
2018-11-26 13:29:29.525  INFO 16252 --- [           main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_191\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_191/bin/server;C:/Program Files/Java/jre1.8.0_191/bin;C:/Program Files/Java/jre1.8.0_191/lib/amd64;C:\Scripts\;C:\;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Python37\;C:\Python37\Scripts;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Git\cmd;C:\Program Files\RedHat\java-1.8.0-openjdk-1.8.0.161-1\bin;C:\WINDOWS\System32\OpenSSH\;C:\MinGW\bin;C:\Program Files\MicrosoftVSCode\bin;C:\cygwin64\bin;C:\Program Files\apache-maven-3.5.4\bin;C:\Users\JulioPHX\AppData\Local\Microsoft\WindowsApps;;C:\Users\JulioPHX\Microsoft VS Code\bin;C:\SpringToolSuite\sts-bundle\sts-3.9.6.RELEASE;;.]
2018-11-26 13:29:29.773  INFO 16252 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-11-26 13:29:29.774  INFO 16252 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4461 ms
2018-11-26 13:29:29.852  INFO 16252 --- [           main] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-11-26 13:29:29.861  INFO 16252 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-11-26 13:29:29.862  INFO 16252 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-11-26 13:29:29.862  INFO 16252 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'formContentFilter' to: [/*]
2018-11-26 13:29:29.862  INFO 16252 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-11-26 13:29:30.698  INFO 16252 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2018-11-26 13:29:30.703  WARN 16252 --- [           main] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=org.apache.derby.jdbc.EmbeddedDriver was not found, trying direct instantiation.
2018-11-26 13:29:31.587  INFO 16252 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-1 - Driver does not support get/set network timeout for connections. (Feature not implemented: No details.)
2018-11-26 13:29:31.596  INFO 16252 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2018-11-26 13:29:31.764  INFO 16252 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-11-26 13:29:31.925  INFO 16252 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.7.Final}
2018-11-26 13:29:31.929  INFO 16252 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2018-11-26 13:29:32.247  INFO 16252 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2018-11-26 13:29:32.586  INFO 16252 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.DerbyTenSevenDialect
2018-11-26 13:29:34.603  WARN 16252 --- [           main] o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget encountered exception accepting command : Error executing DDL "drop table topic" via JDBC Statement

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "drop table topic" via JDBC Statement

Caused by: java.sql.SQLSyntaxErrorException: Schema 'SA' does not exist

Caused by: org.apache.derby.iapi.error.StandardException: Schema 'SA' does not exist

2018-11-26 13:29:34.718  INFO 16252 --- [           main] o.h.t.schema.internal.SchemaCreatorImpl  : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@74b00247'
2018-11-26 13:29:34.725  INFO 16252 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-11-26 13:29:36.108  INFO 16252 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2018-11-26 13:29:36.251  WARN 16252 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2018-11-26 13:29:36.757  INFO 16252 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-11-26 13:29:36.763  INFO 16252 --- [           main] P.ProjectNameWithJpaApplication          : Started ProjectNameWithJpaApplication in 12.543 seconds (JVM running for 13.617)
2018-11-26 13:29:42.083  INFO 16252 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2018-11-26 13:29:42.084  INFO 16252 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2018-11-26 13:29:42.100  INFO 16252 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 16 ms
2018-11-26 13:29:42.298  INFO 16252 --- [nio-8080-exec-1] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory

还有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>PackageNameWithJPA</groupId>
<artifactId>ProjectNameWithJPA</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

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

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

    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derby</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

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


</project>

项目结构:

enter image description here

在此先感谢您的帮助。

4 个答案:

答案 0 :(得分:4)

我有同样的问题。这是因为您的“属性”默认设置为: “ spring.jpa.hibernate.ddl-auto = create-drop”

更改它 在application.properties文件中。如果不在此位置,请添加

  

“ spring.jpa.hibernate.ddl-auto = update”

您的application.properties文件中的

行。它工作正常。

答案 1 :(得分:3)

即使在使用Apache Derby时遇到了相同的错误。这是因为spring的默认属性为-spring.jpa.hibernate.ddl-auto=create-drop

解决方案::在application.properties文件夹中创建一个src/main/resources文件,并将属性更改为spring.jpa.hibernate.ddl-auto=update,然后再次运行该应用程序。

答案 2 :(得分:0)

在软件包“ ProjectNameWithJPA.course”中作为第二个控制器的原因是404错误,因为spring无法扫描“ ProjectNameWithJPA.course”中的控制器。

默认情况下,Spring-Boot在相同的包层次结构下扫描控制器,就像它可以是“ PackageNameWithJPA.course”一样。

阅读此书可进一步了解spring文档[https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html]

答案 3 :(得分:0)

您始终可以在Spring Boot项目中定义自定义组件扫描。默认情况下,@ SpringBootApplication批注处理应用程序的组件扫描。但是,假设其中一个组件是在另一个包中定义的,那么您可以在配置类中定义它,例如:

@ComponentScan({“ com.springboot.basics.springbootPA1”,“ com.springboot.springbootPA2”}) @SpringBootApplication 公共类testApplication {