我已经创建了一个Spring Boot应用程序。当我在嵌入式tomcat中部署jar文件并调用测试API时,它会显示404错误。我可以知道为什么会出错吗?

主类

package com.telematics.fleet;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;


@SpringBootApplication
@ComponentScan(basePackages={"com.telematics.fleet.controller", "com.telematics.fleet.repository",
        "com.telematics.fleet.service","com.telematics.fleet.utility"})
public class TelematicsFleetApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(TelematicsFleetApplication.class, args);
    }
}

控制器类
package com.telematics.fleet.controller;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/app")
public class FleetAppController
{
    @RequestMapping(value="/test", method=RequestMethod.GET)
    public String test()
    {
        System.out.println("Called test API");
        return "Success";
    }
}

控制台
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/dell/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/dell/.m2/repository/org/slf4j/slf4j-log4j12/1.7.25/slf4j-log4j12-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
The Class-Path manifest attribute in C:\Users\dell\.m2\repository\com\mchange\c3p0\0.9.5.2\c3p0-0.9.5.2.jar referenced one or more files that do not exist: file:/C:/Users/dell/.m2/repository/com/mchange/c3p0/0.9.5.2/mchange-commons-java-0.2.11.jar
08:22:29.726 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
08:22:29.738 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
08:22:29.739 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/Malya/Git_Homes/telematics-fleet/target/classes/]

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.0.RELEASE)

2018-03-22 08:22:31.881  INFO 252 --- [  restartedMain] c.t.fleet.TelematicsFleetApplication     : Starting TelematicsFleetApplication on admin with PID 252 (C:\Malya\Git_Homes\telematics-fleet\target\classes started by dell in C:\Malya\Git_Homes\telematics-fleet)
2018-03-22 08:22:31.889  INFO 252 --- [  restartedMain] c.t.fleet.TelematicsFleetApplication     : No active profile set, falling back to default profiles: default
2018-03-22 08:22:32.280  INFO 252 --- [  restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@795b4bba: startup date [Thu Mar 22 08:22:32 IST 2018]; root of context hierarchy
2018-03-22 08:22:47.336  INFO 252 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$8c439cf8] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-03-22 08:22:51.865  INFO 252 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-03-22 08:22:52.015  INFO 252 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-03-22 08:22:52.016  INFO 252 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-03-22 08:22:52.076  INFO 252 --- [ost-startStop-1] 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\jdk1.8.0_162\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_162/bin/server;C:/Program Files/Java/jre1.8.0_162/bin;C:/Program Files/Java/jre1.8.0_162/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;c:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Git\cmd;C:\Program Files (x86)\Skype\Phone\;C:\Program Files (x86)\Cypress\EZ-USB FX3 SDK\1.3\ARM GCC\bin\;C:\Program Files (x86)\Cypress\EZ-USB FX3 SDK\1.3\eclipse\jre\bin\;C:\Program Files (x86)\sbt\bin;C:\modeltech64_10.2c\win64;C:\Program Files (x86)\CodeBlocks\MinGW\bin;C:\Program Files (x86)\CodeBlocks\MinGW;C:\myrWork\ztex-160513\sp3anTest\aes220_win_files_160502-1\aes220_win_files\DLL;C:\myrWork\ztex-160513\sp3anTest\aes220_win_files_160502-1\aes220_win_files\libs\MS32;C:\myrWork\eMMCModel\ss_emmc\eMMC_vip\sdio\rlm\win_64;C:\workspace\eMMCModel\ss_emmc\eMMC_vip\sdio\sv\examples\sim;C:\Malya\tool\sts-bundle\sts-3.9.2.RELEASE;;.]
2018-03-22 08:22:52.790  INFO 252 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-03-22 08:22:52.791  INFO 252 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 20525 ms
2018-03-22 08:23:00.377  INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-03-22 08:23:00.407  INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-03-22 08:23:00.408  INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-03-22 08:23:00.409  INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-03-22 08:23:00.410  INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-03-22 08:23:00.411  INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpTraceFilter' to: [/*]
2018-03-22 08:23:00.412  INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'webMvcMetricsFilter' to: [/*]
2018-03-22 08:23:01.619  INFO 252 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2018-03-22 08:23:03.674  INFO 252 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2018-03-22 08:23:04.327  INFO 252 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-03-22 08:23:04.469  INFO 252 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2018-03-22 08:23:05.269  INFO 252 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate Core {5.2.14.Final}
2018-03-22 08:23:05.284  INFO 252 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2018-03-22 08:23:05.721  INFO 252 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-03-22 08:23:08.342  INFO 252 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2018-03-22 08:23:16.185  INFO 252 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-03-22 08:23:34.747  INFO 252 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@795b4bba: startup date [Thu Mar 22 08:22:32 IST 2018]; root of context hierarchy
2018-03-22 08:23:36.160  WARN 252 --- [  restartedMain] 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-03-22 08:23:37.239  INFO 252 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/app/test],methods=[GET]}" onto public java.lang.String com.telematics.fleet.controller.FleetAppController.test()
2018-03-22 08:23:37.380  INFO 252 --- [  restartedMain] 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.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-03-22 08:23:37.383  INFO 252 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-03-22 08:23:38.325  INFO 252 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-22 08:23:38.326  INFO 252 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-22 08:23:39.279  INFO 252 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-22 08:23:40.156  WARN 252 --- [  restartedMain] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2018-03-22 08:23:46.453  INFO 252 --- [  restartedMain] org.quartz.impl.StdSchedulerFactory      : Using default implementation for ThreadExecutor
2018-03-22 08:23:46.581  INFO 252 --- [  restartedMain] org.quartz.core.SchedulerSignalerImpl    : Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
2018-03-22 08:23:46.582  INFO 252 --- [  restartedMain] org.quartz.core.QuartzScheduler          : Quartz Scheduler v.2.3.0 created.
2018-03-22 08:23:46.588  INFO 252 --- [  restartedMain] org.quartz.simpl.RAMJobStore             : RAMJobStore initialized.
2018-03-22 08:23:46.593  INFO 252 --- [  restartedMain] org.quartz.core.QuartzScheduler          : Scheduler meta-data: Quartz Scheduler (v2.3.0) 'quartzScheduler' with instanceId 'NON_CLUSTERED'
  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  NOT STARTED.
  Currently in standby mode.
  Number of jobs executed: 0
  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
  Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.

2018-03-22 08:23:46.595  INFO 252 --- [  restartedMain] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler 'quartzScheduler' initialized from an externally provided properties instance.
2018-03-22 08:23:46.595  INFO 252 --- [  restartedMain] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler version: 2.3.0
2018-03-22 08:23:46.596  INFO 252 --- [  restartedMain] org.quartz.core.QuartzScheduler          : JobFactory set to: org.springframework.boot.autoconfigure.quartz.AutowireCapableBeanJobFactory@629a27c7
2018-03-22 08:23:47.067  INFO 252 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2018-03-22 08:23:47.271  INFO 252 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/health],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-03-22 08:23:47.274  INFO 252 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/info],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-03-22 08:23:47.279  INFO 252 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto protected java.util.Map<java.lang.String, java.util.Map<java.lang.String, org.springframework.boot.actuate.endpoint.web.Link>> org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping.links(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-03-22 08:23:48.079  INFO 252 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-03-22 08:23:48.086  INFO 252 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-03-22 08:23:48.130  INFO 252 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-03-22 08:23:48.207  INFO 252 --- [  restartedMain] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2018-03-22 08:23:48.208  INFO 252 --- [  restartedMain] o.s.s.quartz.SchedulerFactoryBean        : Starting Quartz Scheduler now
2018-03-22 08:23:48.209  INFO 252 --- [  restartedMain] org.quartz.core.QuartzScheduler          : Scheduler quartzScheduler_$_NON_CLUSTERED started.
2018-03-22 08:23:48.464  INFO 252 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-03-22 08:23:48.488  INFO 252 --- [  restartedMain] c.t.fleet.TelematicsFleetApplication     : Started TelematicsFleetApplication in 78.687 seconds (JVM running for 81.635)
2018-03-22 08:24:55.653  INFO 252 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-03-22 08:24:55.654  INFO 252 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2018-03-22 08:24:55.755  INFO 252 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 101 ms

POSTMAN响应
    {
    "timestamp": "2018-03-22T03:06:40.138+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/telematics-fleet/app/test"
}

属性文件
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword

在控制台服务器上运行正常,但尝试访问api时出现404错误

最佳答案

在将SpringBoot应用程序部署到容器时,要记住两个要点:

1. 应用程序的起点:如果要将SprinBoot应用程序部署到任何servlet container(例如Tomcat),则您的启动程序类必须扩展 SpringBootServletInitializer,以便容器可以找到应用程序的起点

@SpringBootApplication
public class TelematicsFleetApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(TelematicsFleetApplication .class);
    }

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

}
  • Tomcat上成功部署后,应在所有资源URL之前添加应用程序名称的前缀。

  • 示例:localhost:8080/Application_Name/app/test
    额外提示:在Spring 4.3之后,您可以将@RequestMapping(method = RequestMethod.GET)替换为@GetMapping

    示例:@Getmapping("/test")

    09-10 07:47