首页 > 解决方案 > @Import 注册非@Component bean

问题描述

我注意到,即使没有注释的类@Component在注释中声明时也会注册到 Spring 上下文中@Import

@Configuration
@Import({MyBean.class})
class MyConfig {
    @Bean
    Object object(MyBean myBean) { // this works
        return new Object();
    }
}

class MyBean {} // no annotation here

这种行为在文档中不是很清楚@Import

这是想要的吗?它是否记录在某处?@component导入非类和@Component类之间有什么区别吗?

文档说:

允许导入@Configuration 类、ImportSelector 和 ImportBeanDefinitionRegistrar 实现,以及常规组件类

什么是“常规组件类”?任何类或用 注释的类@Component

标签: javaspringspring-context

解决方案


它在java 文档中声明使用ImportResource来导入不是@Configuration

如果需要导入 XML 或其他非@Configuration bean 定义资源,请改用@ImportResource 注解。


推荐阅读