想要让一个普通类接受 Spring 容器管理,有以下方法
- 使用 @Bean 注解
- 使用 @Controller @Service @Repository @Component 注解标注该类,然后再使用 @ComponentScan 扫描包
- @Import 方法,即现在这种方式
Student 类
public class Student {
}
配置类
@Configuration
@Import(Student.class)
public class ImportConfig {
}
测试代码
@Test
public void test() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ImportConfig.class);
String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
for (String name : beanDefinitionNames) {
System.out.println(name);
}
}
观察有没有 Student 产生的 bean
结果
ImportConfig 和 Student 都被加入spring 容器