【Spring Framework】Spring入门教程(四)注册Bean到IOC容器
注册Bean到IOC容器大致分为4种:
①、包扫描+组件注解(@Controller、@Service、@Repository、@Component)
针对类是我们自己编写的情况
②、@Bean注解
针对导入第三方包里面的类的情况
③、@Import
针对快速导入某一个类的情况,如仅仅只是调用无参构造创建对象。
1)@Import注解直接导入
2)ImportSelector手动导入Bean到容器中
3)ImportBeanDefinitionRegistrar手动注册bean到容器中
④、FactoryBean(Bean工厂)
默认获取到的是工厂bean调用getObject方法创建的对象
要获取工厂bean本身,我们需要给id前面加一个&
(&FactoryBean)
实战过Spring的人来说,前两种方式可谓是最常见不过了。而后两种方式在开发中比较少见,因此本文主要介绍@Import和FactoryBean这两种方式。
@Import方式
@Import注解源码:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {
Class<?>[] value();
}
通过源码我们可以发现,@Import注解只能放置在类上,并且有一个value属性,是一个Class类型的数组,我们将需要导入到IOC容器的Bean的字节码放置这个数组中,spring容器就会通过反射创建对象到ioc容器中。
--测试
--配置类
@Configuration
@Import({Color.class, Red.class})
public class SpringConfig {
}
--单元测试
@Test
public void testApplicationContext2() {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
String[] names = context.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
}
--测试结果

ImportSelector方式
ImportSelect是一个接口,接口中有一个抽象方法selectImports,返回值为一个String数组,
spring会自动将返回的String数组中的类创建对象到ioc容器中去。
--MyImportSelector代码
public class MyImportSelector implements ImportSelector {
// 返回值就是导入到容器中的组件的全类名
// AnnotationMetadata:封装了当前标注@Import注解的类的所有注解信息
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[]{"org.cjw.pojo.Blue", "org.cjw.pojo.Yellow"};
}
}
--配置类
@Configuration
@Import({Color.class, Red.class, MyImportSelector.class})
public class SpringConfig {
}
--单元测试
同上
--测试结果

ImportBeanDefinitionRegistrar
这种方式和ImportSelector方式很类似,都是实现一个接口,然后在重写的方法中编写bean的导入规则。
--MyImportBeanDefinitionRegistrar代码
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
// 编写注册判断规则
// 指定Bean的类型,作用域等等
RootBeanDefinition beanDefinition = new RootBeanDefinition(RainBow.class);
// 注册一个bean到ioc容器中,并指定beanName
beanDefinitionRegistry.registerBeanDefinition("rainBow", beanDefinition);
}
}
--配置类
@Configuration
@Import({Color.class, Red.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
public class SpringConfig {
--单元测试
同上
--测试结果

FactoryBean
FactoryBean是一个接口,我们需要编写一个类实现它,并重写getObject、getObejctType、isSingleton方法。
getObject:IOC容器会执行此方法得到Bean,并放到IOC容器中去。
getObjectType:获取Bean的类型。
isSingleton:设置Bean是否为单例,返回值为true为单例,false为多例,ioc容器不管理多例的Bean,只负责创建。
Spring与其他框架进行整合的时候使用的就是FactoryBean来创建对象到IOC容器中。
--ColorFactoryBean代码
public class ColorFactoryBean implements FactoryBean<Green> {
@Override
public Green getObject() throws Exception {
return new Green();
}
@Override
public Class<?> getObjectType() {
return Green.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
--SpringConfig代码
@Configuration
public class SpringConfig {
@Bean
public ColorFactoryBean colorFactoryBean() {
return new ColorFactoryBean();
}
}
--单元测试
@Test
public void testApplicationContext2() {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
Object bean = context.getBean("colorFactoryBean");
System.out.println(bean);
System.out.println(bean.getClass());
}
--测试结果

通过结果我们可以发现,ioc容器确实有ColorFactoryBean这个对象,但是这个对象的本质是一个Green,即是我们需要创建到ioc容器中的bean。因此我们可以得出结论,只要实现了FactoryBean接口的类,spring都会执行它的getObject方法,将创建的对象放入到ioc容器中,spring和第三方框架的整合靠的就是FactoryBean。
【Spring Framework】Spring入门教程(四)注册Bean到IOC容器的更多相关文章
- 无废话ExtJs 入门教程四[表单:FormPanel]
无废话ExtJs 入门教程四[表单:FormPanel] extjs技术交流,欢迎加群(201926085) 继上一节内容,我们在窗体里加了个表单.如下所示代码区的第28行位置,items:form. ...
- PySide——Python图形化界面入门教程(四)
PySide——Python图形化界面入门教程(四) ——创建自己的信号槽 ——Creating Your Own Signals and Slots 翻译自:http://pythoncentral ...
- Elasticsearch入门教程(四):Elasticsearch文档CURD
原文:Elasticsearch入门教程(四):Elasticsearch文档CURD 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接: ...
- RabbitMQ入门教程(四):工作队列(Work Queues)
原文:RabbitMQ入门教程(四):工作队列(Work Queues) 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https:/ ...
- JasperReports入门教程(四):多数据源
JasperReports入门教程(四):多数据源 背景 在报表使用中,一个页面需要打印多个表格,每个表格分别使用不同的数据源是很常见的一个需求.假如我们现在有一个需求如下:需要在一个报表同时打印所有 ...
- Spring Cloud 入门教程(四): 分布式环境下自动发现配置服务
前一章, 我们的Hello world应用服务,通过配置服务器Config Server获取到了我们配置的hello信息“hello world”. 但自己的配置文件中必须配置config serve ...
- 四、Spring中使用@Conditional按照条件注册Bean
以前其实是写过@Condtional注解的笔记的,这里附上链接: Spring中的@conditional注解 但已经忘记的差不多了,所以今天再重新学习下,可以互补着学习 @Contional:按照一 ...
- Spring 5:以函数式方式注册 Bean
http://www.baeldung.com/spring-5-functional-beans 作者:Loredana Crusoveanu 译者:http://oopsguy.com 1.概述 ...
- Spring系列11:@ComponentScan批量注册bean
回顾 在前面的章节,我们介绍了@Comfiguration和@Bean结合AnnotationConfigApplicationContext零xml配置文件使用Spring容器的方式,也介绍了通过& ...
随机推荐
- Leetcode 课程表 C++ 图的深度搜索和广度搜索练习
广度搜索(degree) struct GraphNode{ int label; vector<GraphNode*> neighbours; GraphNode(int x):labe ...
- 测试开发【提测平台】分享14-Vue图标Icon几种用法并利用其一优化菜单
微信搜索[大奇测试开],关注这个坚持分享测试开发干货的家伙. 回归主线更新,由于本次知识点只有一个,就不给思维导图了,在上系列测试平台开发实践中主要学习了页面直接的转跳方法和远程搜索的如何做,最终实现 ...
- Python基础(获取对象信息)
import types print(type('abc') == str)#True print(type(123) == int)#True def f1(): pass print(type(f ...
- thinkphp5 目录结构
/* ├─application 应用目录 │ ├─common 公共模块目录(可以更改) │ ├─module_name ...
- tomcat隐藏版本号
默认报错页面信息会暴露出版本号 进入tomcat的lib目录找到catalina.jar文件 unzip catalina.jar之后会多出两个文件夹 进入org/apache/catalina/ut ...
- PAT A1020——已知后序中序遍历求层序遍历
1020 Tree Traversals Suppose that all the keys in a binary tree are distinct positive integers. Give ...
- FMT 和 子集卷积
FMT 和 子集卷积 FMT 给定数列 $ a_{0\dots 2^{k}-1} $ 求 $ b $ 满足 $ b_{s} = \sum_{i\in s} a_i $ 实现方法很简单, for( i ...
- Qtree V
lmn u 表示 u 所在splay子树最上方点距离最近的白点 rmn u 表示 u 所在splay子树最下方点距离最近的白点 开一个set维护所有虚儿子能走到的最近的白点的距离 考虑pushup, ...
- Redis篇:单线程I/O模型
关注公众号,一起交流,微信搜一搜: 潜行前行 redis 单线程 I/O 多路复用模型 纯内存访问,所有数据都在内存中,所有的运算都是内存级别的运算,内存响应时间的时间为纳秒级别.因此 redis 进 ...
- IO流中的字符输入输出流及try...catch处理流处理中的异常
使用字节流读取中文的问题 import java.io.FileInputStream; import java.io.IOException; /* 使用字节流读取中文文件 1个中文 GBK:占用两 ...