一般在容器中注册组件都使用@Bean或者之前讲的@Import,当然还有包扫描+组件标注注解的方法。今天学了一个工厂Bean的方式注册组件,正好也在学设计模式,研究研究
玩FactoryBean需要搞一个类去实现它,老规矩,类名MyFactoryBean
import org.springframework.beans.factory.FactoryBean;
import test.spring.po.ZhangSan;
public class MyFactoryBean implements FactoryBean<ZhangSan> {
// 返回一个ZhangSan对象,这个对象会添加到容器中
public ZhangSan getObject() throws Exception {
return new ZhangSan();
}
public Class<?> getObjectType() {
return ZhangSan.class;
}
// 是否单例
public boolean isSingleton() {
return false;
}
}
当然还是需要@Bean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(value = "top.blogs")
public class MainConfig {
@Bean
public MyFactoryBean getFactoryBean() {
return new MyFactoryBean();
}
}
最后搞个测试类(还是没习惯用junit)
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import test.spring.config.MainConfig;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Object bean1 = applicationContext.getBean("getFactoryBean");
Object bean2 = applicationContext.getBean("getFactoryBean");
System.out.println(bean1 == bean2);
}
}
当然这里打印的是false,因为前面isSingleton这个方法我返回的是false。还有一点就是getBean("getFactoryBean") 获取的是ZhangSan对象而不是工厂对象,若想获取工厂对象需要在getFactoryBean 前加个& 也就是getBean("&getFactoryBean") ,这里是因为spring的BeanFactory接口为我们定义了FactoryBean前缀为&,如下图