@ComponentScan
is used to find which Spring @Component
beans (@Service
or @Repository
or
Controller
) are available in the classpath so they can be used in the application context. This is a convenient feature especially when
you begin a new project but it comes with the drawback of slowing down the application start-up time especially when the application becomes bigger
(ie: it references a large JAR file, or it references a significant number of JAR files, or the base-package refers to a large amount of .class
files).
@ComponentScan
should be replaced by an explicit list of Spring beans loaded by @Import
.
The interface @SpringBootApplication
is also considered by this rule because it is annotated with @ComponentScan
.
@ComponentScan public class MyApplication { ... } @SpringBootApplication public class MyApplication { ... }
@Configuration @Import({ DispatcherServletAutoConfiguration.class, ErrorMvcAutoConfiguration.class, HttpEncodingAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, MultipartAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, WebMvcAutoConfiguration.class }) public class MyApplication { ... }