spring - @ComponentScan 必须和@Configuration 放在一起吗? ( Spring 芯)

标签 spring applicationcontext

我在很多文章中读到,@ComponentScan 应该和@Configuration 放在一个类的顶部。这里有一些引用:

we use the @ComponentScan annotation along with @Configuration annotation to specify the packages that we want to be scanned (https://www.baeldung.com/spring-component-scanning)

@ComponentScan(basePackages = "com.zetcode") @Configuration public class Application { ... } (http://zetcode.com/spring/componentscan)

The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. (https://dzone.com/articles/spring-component-scan)

我很好奇如果没有 @Configuration 是否会抛出异常。令人惊讶的是,即使没有@Configuration,一切也能正常工作。这里的代码:

@ComponentScan
public class AppConfig {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }
    }
}

我只有一个打印出来的示例 bean。

@Component
public class Car {

}

这是主要方法的输出:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
appConfig
car

为什么有效?为什么他们告诉要在配置中使用它?这是旧要求吗?

更令人惊讶的是,appConfig 变成了一个 bean,即使它没有任何特定的注解,例如 @Configuration 或 @Component。那么这是否意味着任何作为 new AnnotationConfigApplicationContext() 参数的东西都会变成一个 bean,不管它有或没有什么注释?

我可能错过了一些可以证明这一点的核心 spring 行为。有什么想法吗?

最佳答案

您仍在隐式使用 @Configuration@ComponentScan。通过将 AppConfig.class 作为参数传递给上下文,它认为它是配置。这也可以解释为它创建的 bean

关于spring - @ComponentScan 必须和@Configuration 放在一起吗? ( Spring 芯),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63177768/

相关文章:

java - 在 Spring Boot 应用程序中使用 redis 创建存储库

spring - 加载部分 Spring 上下文

java - Dispatcher-servlet 无法映射到 websocket 请求

java - 始终通过上下文在 Spring 服务中注入(inject)一些字段

java - 使用@SpringBean 将 ApplicationContext 注入(inject) Wicket 组件失败

java - SessionAttribute 和 SpringFramework

java - 如何从 session 中打印 bean 值?

java - 全局事务管理-Jboss : Closing a connection for you

spring - JBoss AS 7 Infinispan 集群

json - Spring 是否支持 JSON 配置?