007Spring接口FactoryBean
2018-07-06 本文已影响11人
编程界的小学生
1、简介
FactoryBean给容器中注册一个组件,是一个接口。
2、基础类
public class Color {}
3、FactoryBean
3.1、内置方法
/**
* 返回一个对象
*/
T getObject() throws Exception;
/**
* 返回一个对象的类型
*/
Class<?> getObjectType();
/**
* 是否是单例
*/
boolean isSingleton();
3.2、讲解
3.2.1、需求
利用BeanFactory接口注册Color组件。
3.2.2、工厂类
/**
* 创建一个Spring定义的FactoryBean
*/
public class ColorFactoryBean implements FactoryBean<Color> {
/**
* 返回一个Color对象,这个对象会返回一个Color对象
*/
@Override
public Color getObject() {
return new Color();
}
/**
* 返回一个Color类型
*
* @return
*/
@Override
public Class<?> getObjectType() {
return Color.class;
}
/**
* 是单例吗?
* true:单例
* false:多例
*
* @return
*/
@Override
public boolean isSingleton() {
return true;
}
}
3.2.3、配置类
@Configuration
public class MainConfig {
@Bean
public ColorFactoryBean colorFactoryBean() {
return new ColorFactoryBean();
}
}
3.3.4、测试类
public class FactoryBeanTest {
private final ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(MainConfig.class);
@Test
public void test() {
String[] definitionNames = applicationContext.getBeanDefinitionNames();
for (String name : definitionNames) {
System.out.println(name);
}
// 工厂bean获取的是调用getObject创建的对象
Object colorFactoryBean = applicationContext.getBean("colorFactoryBean");
System.out.println(colorFactoryBean.getClass());
}
}
3.3.5、测试结果
mainConfig
colorFactoryBean
class com.chentongwei.spring.annotation.factorybean.entity.Color
PS:
结果分析:
帮我们注入了colorFactoryBean组件,奇怪的事情来了,为什么类型是Color而不是ColorFactoryBean呢?
FactoryBean要想获取ColorFactoryBean需要在获取bean的方法前面加上&符号。如下测试类:
3.3.6、测试类
public class FactoryBeanTest {
private final ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(MainConfig.class);
@Test
public void test() {
String[] definitionNames = applicationContext.getBeanDefinitionNames();
for (String name : definitionNames) {
System.out.println(name);
}
// 工厂bean获取的是调用getObject创建的对象
Object colorFactoryBean = applicationContext.getBean("colorFactoryBean");
System.out.println(colorFactoryBean.getClass());
Object colorFactoryBean1 = applicationContext.getBean("&colorFactoryBean");
System.out.println(colorFactoryBean1.getClass());
}
}
3.3.9、测试结果
mainConfig
colorFactoryBean
class com.chentongwei.spring.annotation.factorybean.entity.Color
class com.chentongwei.spring.annotation.factorybean.factory.ColorFactoryBean
4、广告
-
码云点star,万分感谢!
代码已经上传到码云了
https://gitee.com/geekerdream/spring-anonation
通用的权限处理框架
https://gitee.com/geekerdream/common-security
通用的异常处理
https://gitee.com/geekerdream/exception-handler
通用的发送邮件
https://gitee.com/geekerdream/common-boot-email
陆续会推出更多干货,希望关注!
-
QQ群【Java初学者学习交流群】:458430385
-
微信公众号【Java码农社区】
- 今日头条号:编程界的小学生