InterviewSolution
| 1. |
Explain the main or entry-level method of Spring Boot Application. |
|
Answer» Main Spring Boot class typically looks like: @SpringBootApplication public class SpringBoot1Application { public static void main(String[] args) { SpringApplication.run(SpringBoot1Application.class, args); } }As you can see above, the main method calls static run() method SpringApplication class and provides itself(the SpringBoot1Application.class) & args. Now the class supplied (SpringBoot1Application.class) is annotated with @SpringBootApplication. Now, SpringBootApplication annotation is defined as : @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 {Where @SpringBootConfiguration is a wrapper Annotation over @Configuration. Considering this, the Application will now look for classes annotated with @Configuration for setting up the configuration & context. For example, a typical configuration might look like: @Configuration public class MyConfiguration { @Bean public MyBean1 myBean() { return new MyBean1(); } @Bean public MyBean2 myBean() { return new MyBean2(); } @Bean public MyBean1 myBean() { return new MyBean1(); } }This configuration creates and registers an instance of BEANS MyBean1, MyBean2 & MyBean3 so that they can be injected in your application classes and used. @ComponentScan instructs the application to scan all ( or filtered if configured so) to look for classes annotated with @Service, @Component, @REPOSITORY & @Controller and register them. You can use include/exclude filters to narrow down the scan. @EnableAutoConfiguration instructs the application to go with default configuration for the boot STARTERS. For example, the default port for the embedded tomcat server is 8080. So to summarize, at bootstrap, your application for @Configuration & initializes and registers configuration. It also looks for components in your packages using ComponentScan and registers them (Building the ApplicationContext). Finally, it executes CODE which initializes configuration with default configuration for the boot starters that you included. |
|