配置 类 在 spring 引导项目中的作用

role of configuration classes in spring boot projects

我是 springboot 应用程序开发的新手,我在这个 url https://start.spring.io/ 的帮助下生成了我的项目,当我在我的 IDE 中打开这个项目时,我有 2 classes 生成 这是第一个class

    public class ServletInitializer extends SpringBootServletInitializer   {
    @Override
    protected SpringApplicationBuilder    configure(SpringApplicationBuilder application) {
        return application.sources(TravellingApplication.class);
    }}

这是第二个class

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

我真的不明白 Servletinitializer class 中的 configure method 里面发生了什么。 如果我删除两个 classes,我可以编写 更好的代码配置 然后做这样的事情,

 class simmilar to dispatcherservlet.xml
 
 @Configuration
 @EnableWebMvc
 @ComponentScan(basePackages = "com.travelliing")
 public class WebConfig extends WebMvcConfigurerAdapter {
 }

  class simmilar to web.xml 

public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws    ServletException { } 
}
    

如果我错了请纠正我。我认为 ServletInitializer classwebAppInitializer 都具有与 implement WebApplicationInitializer 相同的功能。 除了 configure method in servletInitializer class.

@SpringBootApplication 注释的 travellingApplication class 发生了什么,它是否与我的 webConfig Class 相似,它扩展了 WebMvcConfigureAdapter

两个 class 都会加载 Spring 应用程序上下文。

如果您运行您的应用程序与普通java 应用程序一样,将使用带有主要方法(TravellingApplication) 的class。例如,如果您从 Eclipse 执行 运行 As -> Java applciatnion,或者如果您将应用程序打包为 jar 并从命令行 运行 java -jar myApp.jar

Spring如果您将应用程序打包为 war 文件并将其部署在 Tomcat 或其他支持 Servlet 3.0+ 的 Web 服务器中,则 BootServletInitializer 将用于加载应用程序上下文.它基本上取代了 web.xml.

i really don't get it whats happening inside the configure method in my Servletinitializer class.

TravellingApplication 是一个 @Configuration class - 它声明 Spring beans 和其他 Spring 配置,所以这一行 - return application.sources(TravellingApplication.class); 只是加载这个配置(应用程序上下文) .在 main 方法中发生同样的事情。

whats happening with the travellingApplication class annotated with @SpringBootApplication is it simmilar to my webConfig Class which extends WebMvcConfigureAdapter

@SpringBootApplication 只是

的快捷方式
 @Configuration
 @EnableAutoConfiguration
 @ComponentScan

here