i am new to springboot application development and i generated my project with the help of this url https://start.spring.io/ and when i open this project in my IDE i had 2 classes generated this is the first class
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(TravellingApplication.class);
}}
and this is the second class
@SpringBootApplication
public class TravellingApplication {
public static void main(String[] args) {
SpringApplication.run(TravellingApplication.class, args);
}}
i really don't get it whats happening inside the configure method
in my Servletinitializer
class.
i can write better code configuration if i delete both of the classes
and do something like this,
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 { }
}
correct me if i am wrong. i think both ServletInitializer class
and webAppInitializer
is capable of same functionalities since the somehow implement WebApplicationInitializer
.
except for the configure method in servletInitializer class
.
whats happening with the travellingApplication class
annotated with @SpringBootApplication is it simmilar to my webConfig Class
which extends WebMvcConfigureAdapter
Both classes load the Spring application context.
The class with the main method (TravellingApplication
) will be used if you run your application as normal java application. For example if you do Run As -> Java applciatnion from Eclipse or if you package the application as a jar and run java -jar myApp.jar
from the command line.
SpringBootServletInitializer will be used to load the application context if you package the application as a war file and deploy it in Tomcat or another web server that supports Servlet 3.0+. It basically replaces the web.xml
.
i really don't get it whats happening inside the configure method in my Servletinitializer class.
TravellingApplication is a @Configuration class - it declares Spring beans and other Spring configuration, so this line - return application.sources(TravellingApplication.class);
just loads this configuration (application context). The same thing that happens in the main method.
whats happening with the travellingApplication class annotated with @SpringBootApplication is it simmilar to my webConfig Class which extends WebMvcConfigureAdapter
@SpringBootApplication
is just a shortcut to
@Configuration
@EnableAutoConfiguration
@ComponentScan
See here.