Select Page

Spring Annotations and Component Scanning

Written by Buddhi

2018-05-01

Best practices for defining components and scanning them

Annotate the class by including the exact place where to scan for components with @ComponentScan({“com.app.service”,” com.app.repo”}) rather than providing a path like @ComponentScan(“com”) or @ComponentScan(“com.app”)

Stereotype Annotations

Spring provides predefined annotations that can be used to define specific roles or purposes of that component. @ComponentScan will scan for the annotations.

@Component is the main stereotype annotation in Spring.

Annotations defined below uses @Component implicitly.

  1. @Service
  2. @Repository
  3. @Controller
  4. @RestController
  5. @Configuration

Meta Annotations

Meta annotations are written by developers using the predefined stereotype annotations or annotations which can be used to annotate other annotations.

E.g of custom annotation:


@Retention(RetentionPolicy.Runtime) @Target(ElementType.Type) @Service @Transctional(timeout=60) public @interface MyTransactionalService { String value() default ""; }
@ComponentScan("com.app.service") recognises the above custom annotation and scans it. @MyTransactionalService public class TransferServiceImpl implements TransferService{ ... }

How to define Spring Beans?

  • Explicitly using @Bean annotation on methods inside configuration class. ie., classes annoted with @Configuration annotation
  • Implicitly using @Component and component scanning @ComponentScan

@PostConstruct and @PreDestroy

  • @PostConstruct: Method called at startup after all dependencies are injected. Initialization phase. E.g.: connecting to database after bean creation and dependencies are injected.
  • @PreDestroy: Method called at shutdown pripr to destroying the bean instance. Cleanup phase. E.g.: closing connections after query to db.

Related Articles

List users in windows

List users and groups in Windows Type Users in search box or enter lusrmgr.msc in Run dialog box Win+R -> lusrmgr.msc -> enter

Using scp to copy files

Copy file from local pc to remote server   scp <filename> <useronremotesystem>@<ipaddressofremotesystem>:<remotedirpath>/<remotefilename> scp mytext.txt user2@192.168.1.25:/home/user2/mytext.txt  Copy file from remote server to local pc…

Docker and Docker Compose

Docker Compose docker-compose.yml file contains the command to run, start, stop all the containers and services mentioned inside the file. up build or create or recreate container and start it docker-compose up build build the container but won’t start it…