InterviewSolution
| 1. |
Can you explain Component Scanning in Spring Boot? |
|
Answer» If you use @SpringBootApplication annotation, it brings in default Component scan which will scan the root or base packages where your main class annotated with @SpringBootApplication is located and all its sub-packages. It will also consider your main class as one of the configuration CLASSES as it is annotated (IMPLICITLY) with @Configuration ( This is INCLUDED by @SpringBootApplication annotation). This is equivalent to the following definition : @Configuration @ComponentScan public class MySpringBootApplication { public static void main(String[] args) { SpringApplication.run(MySpringBootApplication.class, args); } }Typically, in your application, you may want to limit the component scan to certain packages. You can achieve that by specifying the base package, for example, @ComponentScan("com.example.demo.myapp")This will scan for all Spring components inside com.example.demo.myapp package ( When we say Spring Components we mean Classes annotated with @Service, @Component, @Repository & @Controller etc.) If you would like to scan multiple packages, it would be : @ComponentScan({"com.example.demo.myapp1",”com.example.demo.myapp2”})Type-safe alternative would be : @ComponentScan(basePackageClasses = {com.example.demo.myapp1.Example1.class, com.example.demo.myapp2.Example2.class})Here Example1.class acts as a marker class for package com.example.demo.myapp1 , when you specify this class , it will scan all other classes from the package com.example.demo.myapp1 along with Exmaple1.class. Similar is the CASE for myapp2 package. @ComponentScan(basePackages = "com.mypackage", includeFilters = @Filter(type = FilterType.REGEX, pattern="com.mypackage.*.*subpackage"), excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = NotToBeScannedClass.class))Here Regex FilterType is used for inclusion which means any class whose package matches the pattern (com.mypackage.*.*subpackage) will be included in the scan while using AssignableType Filter, we have SPECIFIED that a particular class should not be included in scanning. @ComponentScan(basePackages = "com.mypackage", includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = MyCustomAnnotation.class)})MyAnnotation is defined as : @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation { }Here any class that is annotated with MyCustomAnnotation annotation will be included in the scan. |
|