In
this post, I am going to explain
EmployeeService.java
Test.java
a.
What
is component scan?
b.
How
can we communicate component scan information to spring boot?
c.
Example
Application using component scan
What is Component
Scan?
Spring
is a dependency injection framework, where objects define their dependencies
using spring annotations. Suppose an object ‘obj1’ is using other objects obj2,
obj3. In the source code, ‘obj1’ mention its dependencies obj2, obj3 through
some annotations like @Bean constructor arguments, arguments to a factory
method, or properties that are set on the object instance after it is constructed
or returned from a factory method.
The
basic step in spring dependency injection is, to add right annotations
@Component or @Service or @Repository, and tell spring about the packages to be
scanned to get these components.
package
com.sample.model;
import
org.springframework.stereotype.Component;
@Component
public
class Employee {
}
For
example, I added @Component annotation on class Employee, it indicates that Employee class is a "component". Such classes are considered as
candidates for auto-detection, when using annotation-based configuration and class
path scanning.
How can we
communicate component scan information to spring boot?
By
using '@ComponentScan' annotation, we can specify the packages to be scanned
for components. Spring scan all the packages mentioned in @ComponentScan
annotation and automatically create beans for every class annotated with
@Component, @Service, @Controller, @RestController, @Repository.
Example
@ComponentScan({"com.sample.model",
"com.sample.service"})
Example Application
using component scan
Employee.java
package com.sample.model; import org.springframework.stereotype.Component; @Component public class Employee { }
EmployeeService.java
package com.sample.service; import org.springframework.stereotype.Component; @Component public class EmployeeService { }
Test.java
package com.sample.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan({"com.sample.model", "com.sample.service"}) public class Test { public static void main(String args[]) { ApplicationContext applicationContext = SpringApplication.run(Test.class, args); for (String name : applicationContext.getBeanDefinitionNames()) { System.out.println(name); } } }
Run
the application Test.java, you can able to see the bean names, employee,
employeeService in the output.
Note
If
there is only one package to scan for components, you can specify like below.
@ComponentScan("com.sample.model")
No comments:
Post a Comment