springboot 无法运行test springboot启动不了_spring

报如上错误;显示应用程序没有显式映射,也就是说,你的Controller(指示Spring某个类是否能够接收HTTP请求),没有映射到启动函数上。

解决办法:

 

springboot 无法运行test springboot启动不了_spring boot_02

在src/main/java/test/TestApplication.class中,为注解@SpringBootApplication加上参数,如图,是我创建Controller时的文件路径名称。而后,重启Spring Boot项目,Over。

springboot 无法运行test springboot启动不了_spring boot_03

 

注:浏览器地址栏输入:localhost:8080/hello

不要前缀,http://localhost:8080/hello

另,8080端口可修改。 

延伸:

深层原因:

首先,我了解到,@SpringBootApplication会扫描当前包及其子包,如果报上述错误,意味着,我们的Controller既不在当前包下,也不属于子包。确实如此。

1、

springboot 无法运行test springboot启动不了_spring_04

可看到,我的controller是注解@SpringBootApplication所在包test 的邻居,所以不在当前包。

2、

springboot 无法运行test springboot启动不了_spring boot_05

我的 controller用的注解是@RestController。经查,@SpringBootApplication注解的子包包括@Controller,@Service,@Component,@Configuration和@Bean注解等。是故,我的controller注解也不是子包注解。

因而,@SpringBootApplication注解并不知道我的controller的存在。故而,我的controller类等于没写。

所以,需要给@SpringBootApplication指条路。

我们查看@SpringBootApplication源码,

@AliasFor(
annotation=ComponentScan.class,
attribute="basePackages"
)
String[] scanBasePackages() default{};

@AliasFor(
annotation=ComponentSacn.class,
sttribute="basepackageClasses"
)
Class<?>[] scanBasePackageClasses() default{};

根据命名,我们可以猜到,这就是两种指路方法,一种指到你家,扫描你家里所有人,另一种经过你家指到你这个人,即class类。显然,我们根据需要进行选择。两种的区别,显然的。

因而,我们选择两种方法的解决方式,为:

package com.wfy.test

//import com.wfy.controller.HelloController;
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootapplication

//@SpringBootApplication(scanBasePackages="com.wfy.controller")
@SpringBootApplication(sacnBasePackageClasses=com.wfy.controller.HelloController.class)
//@SpringBootApplication(scanBasePackageClassees=HelloController.class)
//@SpringBootApplication
public class TestApplication{
public static void main(String[] args){
Springapplication.run(TestApplication.class,args);
}
}

注意,指到你这个人的时候,你可以在参数里写完整的地址,也可以import一下你的地址,在参数里只写名加.class即可。具体看图。(没有双引号)

So,只要我在@SpringBootApplication所在包下创建我的MyController,就不需要指路。无论是用@Controller @ReponseBody,或者@RequstController,都可以扫描到。

springboot 无法运行test springboot启动不了_spring_06

springboot 无法运行test springboot启动不了_spring_07

springboot 无法运行test springboot启动不了_spring boot_08

 

 

 端口号不是8080啊。当然可以改了。

springboot 无法运行test springboot启动不了_重启_09

看路径,resources下,application.properties文件,加代码

springboot 无法运行test springboot启动不了_java_10

 

OK,目前,我有两个在不同位置的controller,我想运行他俩,结果

springboot 无法运行test springboot启动不了_spring_11

 

想着多注解吧,报错。想想也知道重复了,还是想试一下。

搜了一下,原来路径可以多写。再细看源码,原来是一个字符数据啊。 

String[] scanBasePackages() default{};

springboot 无法运行test springboot启动不了_重启_12

 Over。多说无益。下次再聊。