(一)Whitelabel Error Page错误

前言

在学习Spring Boot时遇到

This application has no explicit mapping for /error, so you are seeing this as a fallback.

特此记录

原因

用@SpringBootApplication标注的类的位置不对

错误提示:
(一)Whitelabel Error Page错误_第1张图片
包结构(错误的):
(一)Whitelabel Error Page错误_第2张图片

源码解析

@SpringBootApplication:Spring Boot应用标注在某个类上说明这个类是Spring Boot的主配置类,Spring Boot就应该运行这个类的main方法来启动SpringBoot应用

用SpringBootApplication标注的类

@SpringBootApplication
public class Cb414Application {
     

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

}

而@SpringBootApplication的源代码是:(重点关注@EnableAutoConfiguration)

SpringBootApplication

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
      @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
     
	
	...

}

以前我们需要配置的东西,SpringBoot帮我们自动配置;@EnableAutoConfiguration告诉Spring Boot开启自动配置功能;这样自动配置才能生效(自动配置扫描包,注册什么的…)

EnableAutoConfiguration

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
     

	...

}

AutoConfigurationPackage

自动配置包

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
     

	...

}

Spring的底层注解@Import,给容器中导入一个组件;导入的组件由AutoConfigurationPackages.Registrar.class决定
其中:

AutoConfigurationPackages.Registrar.class:将主配置类(@SpringBootApplication所标注的类)所在的包下面所有的组件都扫描进Spring容器中
这就是上述错误的原因

你可能感兴趣的:(Spring)