1 package org.springframework.beans.factory; 2 3 import org.springframework.lang.Nullable; 4 5 public interface FactoryBean<T> { 6 String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType"; 7 8 @Nullable 9 //返回具体的对象 10 T getObject() throws Exception; 11 12 @Nullable 13 //返回对象的具体类型 14 Class<?> getObjectType(); 15 16 //是否是单例,默认为单例 17 default boolean isSingleton() { 18 return true; 19 } 20 }
创建一个User类,实现此接口
1 package com.study.factoryBean; 2 3 import org.springframework.beans.factory.FactoryBean; 4 import org.springframework.stereotype.Component; 5 6 /** 7 * @author Young 8 * @version 1.0 9 * @date 2021/8/5 12:00 10 */ 11 @Component 12 public class UserFactoryBean implements FactoryBean<User> { 13 @Override 14 public User getObject() throws Exception { 15 return new User("张三","13"); 16 } 17 18 @Override 19 public Class<?> getObjectType() { 20 return User.class; 21 } 22 23 @Override 24 public boolean isSingleton() { 25 return true; 26 } 27 }
创建启动类 此demo采用的是注解模式
package com.study.factoryBean; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * @author Young * @version 1.0 * @date 2021/8/5 13:50 */ public class Demo { public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(); //如果在此处()中,加入扫描路径则不需要调用refresh方法
//指定包扫描路径 applicationContext.scan("com.study.factoryBean"); applicationContext.refresh(); //user类 User user = applicationContext.getBean(User.class); System.out.println(user); //userFactoryBean代理类 com.study.factoryBean.UserFactoryBean$$EnhancerBySpringCGLIB$$ff2ffcf@6b53e23f Object bean = applicationContext.getBean("&userFactoryBean"); System.out.println(bean); //user Object user1 = applicationContext.getBean("userFactoryBean"); System.out.println(user1); } }
总结
FactoryBean和BeanFactory都是Spring创建bean的一种方式
FactoryBean没有BeanFactory创建的过程那么的繁琐
FactoryBean在实现了在getBean时,如果增加了‘&’符号,则get到的为实现FactoryBean接口的代理类,如果不加‘&’则获取到的为getObject方法的实现