使用FactoryBean注册组件
需要实现FactoryBean接口,然后在Config配置类中通过@Bean注入
直接看代码
package com.demon.factory;
import com.demon.bean.Color;
import org.springframework.beans.factory.FactoryBean;
/**
* @author Demon-HY
* @date 2019-12-10
*/
public class ColorFactoryBean implements FactoryBean<Color> {
// 返回一个Color对象,该对象会被添加到容器中
@Override
public Color getObject() throws Exception {
return new Color();
}
// 返回对象的类型
@Override
public Class<?> getObjectType() {
return Color.class;
}
// 是否单例
@Override
public boolean isSingleton() {
return true;
}
}
配置类
package com.demon.config;
import com.demon.factory.ColorFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* 配置类
* @author Demon-HY
* @date 2019-12-9
*/
@ComponentScan(value = "com.demon")
@Configuration
public class Config2 {
@Bean
public ColorFactoryBean colorFactoryBean() {
return new ColorFactoryBean();
}
}
编写测试用户
// FactoryBean
@Test
public void test5() throws Exception {
// 通过注解方式生成 Spring 上下文
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config2.class);
// 这里获取 bean 实际上获取的是Color的实例
Object bean = context.getBean("colorFactoryBean");
Object bean2 = context.getBean("colorFactoryBean");
// 对象类型
System.out.println(bean.getClass()); // class com.demon.bean.Color
// 验证是否单例
System.out.println(bean == bean2); // true
// 获取 ColorFactoryBean 本身的实例
Object bean3 = context.getBean("&colorFactoryBean");
System.out.println(bean3.getClass()); // class com.demon.factory.ColorFactoryBean
ColorFactoryBean bean4 = context.getBean(ColorFactoryBean.class);
System.out.println(bean4.getClass()); // class com.demon.factory.ColorFactoryBean
}
总结一下,目前学到的四种容器注册组件方式
- @Controller,@RestController,@Service,@Repository,@Component
- @Bean
- @Import
- 使用 Spring 提供的 FactoryBean
咖啡小馆
QQ群: 823971061 点击按钮入群
1757

被折叠的 条评论
为什么被折叠?



