1. 类注入到容器的方法
- 注册自己的组件:包扫描(ComponentScan)+@Controller,@Service,@Repository, @Component
- @Bean: 导入第三方组件
- @Import
- 可以快速给容器中导入一个组件,id默认是全类名
- 也可以使用ImportSelector一次型导入多个,导入的是全类名
- ImportBeanDefinitionRegistrar: 手动注册bean到容器
- FactoryBean
- 默认获取到的是工厂bean创建的对象
- (&+id)可以获得工厂bean的本身
2. 实例
1. 打印注入到容器中的bean
public class ConfigDemo {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
Arrays.stream(context.getBeanDefinitionNames()).forEach(p -> System.out.println(p));
}
}
2. 用@Bean注入bean
@Configuration//相当于以前的配置文件
public class MainConfig {
@Scope(scopeName = "prototype")
@Bean(name = {"person"})//容器中该bean的id默认是方法的名字
public Person person1() {
return new Person("test", 20);
}
}
3. 用@ComponentScan + @Controller,@Service注入bean, bean name默认是class的名字
在"com.test.tornesol.util.spring_annotation"包下定义@Controller,@Service注解的class,即可注入到容器中。注意:使用@ComponentScan定义的filter,对其他方式的注入,并不起作用。也就是说,三种注入方式是相互独立的。
@Configuration
@ComponentScan(
basePackages = {"com.test.tornesol.util.spring_annotation"},
includeFilters = {@ComponentScan.Filter(type = FilterType.CUSTOM, classes = {MyTypeFilter.class})},
useDefaultFilters = false
)
public class MainConfig {
@Scope(scopeName = "prototype")
@Bean(name = {"person"})//容器中该bean的id默认是方法的名字
public Person person1() {
return new Person("test", 20);
}
}
4. 使用@Import
@Configuration//相当于以前的配置文件
@ComponentScan(
basePackages = {"com.test.tornesol.util.spring_annotation"},
includeFilters = {@ComponentScan.Filter(type = FilterType.CUSTOM, classes = {MyTypeFilter.class})},
useDefaultFilters = false
)
@Import({Red.class, MyImportSelector.class, MyImportBeanDefinition.class})
public class MainConfig {
@Scope(scopeName = "prototype")
@Bean(name = {"person"})//容器中该bean的id默认是方法的名字
public Person person1() {
return new Person("test", 20);
}
}
5. FactoryBean
定义FactoryBean
public class MyFactoryBean implements FactoryBean<MyBean> {
//这个对象返回到容器中
@Override
public MyBean getObject() throws Exception {
return new MyBean();
}
@Override
public Class<?> getObjectType() {
return MyBean.class;
}
@Override
public boolean isSingleton() {
return true;
}
注入factory bean
@Bean
public MyFactoryBean getFactoryBean() {
return new MyFactoryBean();
}
6. 输出
person--> @Bean方式注入
controllerTest-->@ComponentScan+@Controller
myTypeFilter
serviceTest-->@ComponentScan+@Service
com.test.tornesol.util.spring_annotation.config_anno.Red --->@Import
com.test.tornesol.util.spring_annotation.config_anno.White--->@Import
com.test.tornesol.util.spring_annotation.config_anno.Blue--->@Import
yellow--->@Import(register bean)
getFactoryBean-->FactoryBean 注入的。注意bean的类型是FactoryBean.getObject()返回的类型,也就是MyBean