【问题标题】:Spring boot component scan include a single class [duplicate]Spring Boot组件扫描包括单个类[重复]
【发布时间】:2016-06-10 22:07:16
【问题描述】:

我正在使用 spring 组件扫描来自动检测 bean:

@ComponentScan({"com.org.x, com.org.y"})

问题是我希望扫描 com.org.x 中的所有类,但我希望单独从 com.org.y 扫描单个类 com.org.y.SomeService.class

我怎样才能做到这一点?

除了使用上下文扫描之外,我如何创建这个 bean 并注入应用程序上下文?

【问题讨论】:

  • 如果您只想要一个 bean,为什么要使用扫描。只需在配置类中使用 @Bean 注释方法定义您的 bean。 docs.spring.io/spring/docs/current/spring-framework-reference/…
  • @JBNizet 你能给我一个sn-p吗
  • 我提供了一个文档链接,其中包含 sn-ps、解释和所有内容。
  • @JBNizet 你能把它作为答案发布,这样我就可以接受它

标签: java spring spring-boot spring-annotations component-scan


【解决方案1】:

@Import(com.org.y.SomeService.class) 在我的情况下有效(即使 SomeService@Service,而不是 @Configuration

【讨论】:

    【解决方案2】:

    您应该在配置类中使用带有@Bean 注释的方法来定义您的bean,如the documentation 中所述。

    【讨论】:

    • 拥有@Autowired 字段的@Component 怎么样?
    • 是的。非默认构造函数也是如此:如果 SomeService 在构造函数中有参数,则必须将它们复制到实例化的 @Bean 方法中。
    猜你喜欢
    • 2019-02-16
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 2015-12-12
    • 1970-01-01
    相关资源
    最近更新 更多