In
this post, you are going to learn,
a.
How
to define main application class
b.
Example
Application
By
placing the @SpringBootApplication annotation on main class, you can tell
spring boot about the main application class.
The
definition of @ SpringBootApplication annotation is like below.
@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 {
}
As
you see the above definition, SpringBootApplication is annotated with @SpringBootConfiguration,
@EnableAutoConfiguration and @ComponentScan. It means, if you declare any class
with the annotation @SpringBootApplication, then it automatically do components
scan, enable auto configuration.
For
example, as you see above image, Application.java is defined in root package
com.sample.myApp.
Example Application
Employee.java
package com.sample.myApp.model; import org.springframework.stereotype.Component; @Component public class Employee { }
EmployeeService.java
package com.sample.myApp.service; import org.springframework.stereotype.Component; @Component public class EmployeeService { }
The
Application.java file would declare the main method, along with the basic
@SpringBootApplication, as follows:
Application.java
package com.sample.myApp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.ApplicationContext; @SpringBootApplication public class Application { public static void main(String args[]) { ApplicationContext applicationContext = SpringApplication.run(Application.class, args); for (String name : applicationContext.getBeanDefinitionNames()) { System.out.println(name); } } }
Run
the application Application.java, you can able to see the bean names, employee,
employeeService in the output.
No comments:
Post a Comment