4

I and my friend were discussed about @ComponentScan and @Import. Which one is better? We have 2 different ideas.

  1. @ComponentScan: Easy to use, import all beans from the component scan.
  2. @Import: You need to know what component you want to use, no need to scan all.

How about your idea? Which one is better for you to use?

Thanks!

Faraz
  • 6,025
  • 5
  • 31
  • 88
Hoan Nguyen
  • 41
  • 1
  • 3

2 Answers2

4

@Import is used to import Java configuration classes marked with @Configuration/@Component typically. So if you have a bean inside this component, Spring will load it into Application Context. You can just put the name of the component or class and Spring will pull it up for you.

However, by using @ComponentScan, you tell the application which packages to scan for java classes are annotated with @Configuration/@Component (or any of @Component's sub-annotations like @Service or @Repository etc) and load all of them up in Application Context so they can be autowired when required. If there are inner instances that need to be populated, Spring will take care of it.

You can read more about @Import and @ComponentScan on their respective doc pages.

This page explains pretty well the difference.

Faraz
  • 6,025
  • 5
  • 31
  • 88
0

@ComponentScan scans and searches for any beans inside packages/classes specified under basePackageClasses or basePackages options, whichever is configured. This option also allows you to filter some classes that you do not want to be included in search.

@Import is like clubbing one java configuration into another. eg:

@Configuration
@ComponentScan(basePackages="com.stackoverflow")
public class Dbconfig {

  @Bean
  public Datasource dSource(){
   return new Datasource()
  }
}



@Configuration
@Import(Dbconfig.class)
@ComponentScan(basePackages="org.hellospring")
public class AppConfig {

...// beans
}

So here, if we check AppConfig class, it will include all beans registered in Dbconfig configuration class including inside of package com.stackoverflow
+

It will include all beans inside AppConfig class and beans under package org.hellospring

swapyonubuntu
  • 1,952
  • 3
  • 25
  • 34