繁体   English   中英

Spring 引导:ComponentScan 与自动配置的 Jar 中声明的 Bean

[英]Spring Boot: ComponentScan vs Declared Bean in an Autoconfigured Jar

假设我有一个 jar 和一个名为MyComponent的 Spring 组件。 This jar is a Spring Boot "autoconfigured" jar, meaning that it has a Configuration class (annotated with @Configuration ), and additionally, a META-INF/spring.factories file on the classpath. 这个 jar 本身不是可执行的 jar; 它是一个用于包含在 Spring 引导应用程序中的库。

这些文件如下所示:

MyComponent.java ,在 package com.mine.components

@Component
public class MyComponent {

    private static final Logger logger = LoggerFactory.getLogger(MyComponent.class);

    @PostConstruct
    public void init() {
        logger.info("MyComponent inited");
    }
}

MyConfiguration.java ,在 package com.mine.config

@Configuration
@ComponentScan(basePackages = "com.mine.components")
public class MyConfiguration {
}

spring.factories ,在src/main/resources下的META-INF中:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.mine.config.MyConfiguration

如果我在具有上述三个文件的 Spring 引导项目中包含此 jar,则未检测到MyComponent组件(永远不会打印日志消息)。

但是,如果我改为删除@ComponentScan并使用@Bean注释声明MyComponent ,如下所示,它会被检测到:

@Bean
public MyComponent myComponent() {
    return new MyComponent();
}

为什么?

ComponentScan 和 @Configuration class 中声明的 Bean 之间的区别:

@ComponentScan:您启用自动扫描(默认使用当前文件夹路径),您可以选择指定一个 basePackage spring 将在其中找到您的 bean。

@ComponentScan(basePackages = "com.mine.components") 您对 Spring 说,在这个包(“com.mine.components”)中,您通常会使用注释(@Component、@Entity、@控制器、@Service、@Repository 或更多)。

@Bean:这样你在@Configuration class 中手动定义你的bean,但是Spring 必须发现你的配置class,通常使用@ComponentScan,@SpringBootApplication。

META-INF/spring.factories:你定义一个自定义的自动配置

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM