where to place componentscan

Viewed 2273

I have spring mvc application with complete annotations. Where is the best place to add @componentScan? Let me know any of these recommended

  1. class that extends AbstractAnnotationConfigDispatcherServletInitializer?
  2. class that extend WebMvcConfigurationSupport
  3. class that extend WebSecurityConfigurerAdapter

I placed in 2 without security and workign fine. When I added security, I got problem with security config not able to find userdetails service. Then I moved to 3. I found other issues with security and put code to just reuturn null instead of securityconfig object from getRootConfigClasses(). Then I got issues of controllers not found. I am able to fix it to put componenentscan in 2.

I just want to know any links and how it works. Is it ok to put @componentscan in all of these 3? Appreciate your help.

1 Answers

It depends on your project's package tree and what you want to scan. If you want to scan all annoted classes with such annotations like : @Configuration, @Component, @Repository, etc... put @ComponentScan at the top of your package tree.

You can also use the basePackages attribute to specify where to start the scanning.

Say you have an application packages organized like this :

com.app.config,com.app.config.web, com.app.services, com.app.web.controllers

If you want to scan all annoted classes, put the class annoted with @ComponentScan in com.app package.

If you want to scan only controller, add @ComponentScan(basePackages="com.app.web.controllers")

It's up to you to decide.

Related