spring-IoC:将ComponentScan放在哪里



这里是我的春季配置程序:

@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");
}
}

尽管如此,它从未达到。

这里是我的应用程序类:

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

正如您所看到的,@ComponentScan被放置在主ProjectApplication类上。

我已经意识到,当我从主ProjectApplication类中删除@ComponentScan时,就会检测到我的WebSecurityConfiguration

如果存在WebSecurityConfiguration,则忽略它。

有什么想法吗?

SpringBootApplication在不指定@ComponentScan的情况下,默认扫描当前中的所有类以及位于子包中的类,以拾取BeansConfiguration以及其他填充。如果指定

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

则只有CCD_ 11和CCD_。因此,尝试将包含@SpringBootApplication的类放在项目的根目录中,或者使用@SpringBootApplication(scanBasePackages = {'package1', 'package2'})指定必须扫描的包。

首先尝试依赖春季启动默认约定:

假设您已将ProjectApplication放置在com.mycompany.myapp包中您可以:

  1. 从中删除@ComponentScan注释
  2. WebSecurityConfiguration类放在同一个包com.mycompany.myapp或其下的任何包中:示例:com.mycompany.myapp.web.security.config

当spring-boot应用程序默认启动时,它有一个定义良好的策略来确定应该扫描什么,因此它扫描应用程序本身的包(用@SpringBootApplication注释的文件所在的包(及其下面的包。

您可以使用@ComponentScan更改这种行为,但在春季启动驱动的测试中可能会出现问题。所以我认为你不应该毫无理由地去那里。当然,如果您有更改默认组件扫描策略的实际原因,请与我们分享,以便我们的同事/我可以尝试提出解决方案。

最新更新