spring IoC: where to put ComponentScan

163 Views Asked by At

Here my spring configurer:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
@Slf4j
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        log.info("Web security performing");

        http
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .cors().and()
        .csrf().disable()
        .authorizeRequests().anyRequest().permitAll();

        log.info("Web security performed");
    }
}

Nevertheless, it's never reached.

Here my application class:

@ComponentScan({
    "cat.gencat.catsalut.hes.core.domain.mpi",
    "cat.gencat.catsalut.hes.core.repository"
})
@SpringBootApplication(exclude = JmxAutoConfiguration.class)
public class ProjectApplication {

As you can see, @ComponentScan is placed on main ProjectApplication class.

I've realized that when I remove @ComponentScan from my main ProjectApplication class, my WebSecurityConfiguration is detected.

When it's present, WebSecurityConfiguration is ignored.

Any ideas?

2

There are 2 best solutions below

0
badger On

SpringBootApplication without specifying @ComponentScan by default scan all classes in the current and those that are located in subpackages for picking Beans and Configuration and other stuffs. if you specify

@ComponentScan({
    "cat.gencat.catsalut.hes.core.domain.mpi",
    "cat.gencat.catsalut.hes.core.repository"
})

then only cat.gencat.catsalut.hes.core.domain.mpi and cat.gencat.catsalut.hes.core.repository and their subpackages will be scanned for beans. so try to put the class which contains @SpringBootApplication in the root of your project or use @SpringBootApplication(scanBasePackages = {'package1', 'package2'}) to specify packages that have to be scanned.

2
Mark Bramnik On

Try to rely on spring boot default conventions first:

Assuming you've placed ProjectApplication in the com.mycompany.myapp package You can:

  1. Remove the @ComponentScan annotation from it
  2. Place WebSecurityConfiguration class in the same package com.mycompany.myapp or any package beneath it: Example: com.mycompany.myapp.web.security.config.

When spring boot application starts by default it has a very well defined policies of what should be scanned, so it scans the package of the application itself (the package where the file annotated with @SpringBootApplication resides) and the packages beneath it.

You can alter this behavior with @ComponentScan , but then you might have issues in spring boot driven tests. So without a reason I don't think you should really go there. Of course, if you have an actual reason of altering the default component scanning policies, please share so that our colleagues/me could try to come up with a solution.