微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

spring IoC:将 ComponentScan 放在哪里

如何解决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 类中。

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

当它存在时,WebSecurityConfiguration 将被忽略。

有什么想法吗?

解决方法

SpringBootApplication 不指定 @ComponentScan 默认情况下扫描当前所有类和位于子包中的类,以选择 BeansConfiguration 等内容。如果你指定

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

然后只会扫描 cat.gencat.catsalut.hes.core.domain.mpicat.gencat.catsalut.hes.core.repository 及其子包的 bean。所以尝试将包含 @SpringBootApplication 的类放在项目的根目录中,或者使用 @SpringBootApplication(scanBasePackages = {'package1','package2'}) 指定必须扫描的包。

,

首先尝试依赖 spring boot 默认约定:

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

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

spring boot 应用程序默认启动时,它有一个很好定义的应该扫描什么的策略,所以它扫描应用程序本身的包(用 @SpringBootApplication 注释的文件所在的包)和包在它下面。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。