SpringBoot扩展功能之FactoryBean

FactoryBean接口作用

FactoryBean接口是SpringBoot提供的接口,主要用于创建bean。

public interface FactoryBean<T> {

	String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";


	@Nullable
	T getObject() throws Exception;


	@Nullable
	Class<?> getObjectType();


	default boolean isSingleton() {
		return true;
	}
}

说明:

  1. T getObject():返回FactoryBean创建的bean实例,如果isSingleton()返回true,则该实例会放到Spring容器中单例实例缓存池中。

  2. boolean isSingleton():返回由FactoryBean创建bean实例的作用域是singleton还是prototype。

  3. Class getObjectType():返回FactoryBean创建的bean类型。

用法

@Data
public class FirstSunpyBean {

    private String name = "马大帅";
    private Integer age = 52;
}

@Component
public class SunpyFactoryBean implements FactoryBean<FirstSunpyBean> {

    @Override
    public FirstSunpyBean getObject() throws Exception {
        FirstSunpyBean firstSunpyBean = new FirstSunpyBean();
        firstSunpyBean.setName("范德彪");
        firstSunpyBean.setAge(25);
        return firstSunpyBean;
    }

    @Override
    public Class<?> getObjectType() {
        return FirstSunpyBean.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

@Slf4j
@Service
public class MenuServiceImpl {

    public Map<String, String> testMenu() {
        Map<String, String> resultMap = new HashMap<>();
        FirstSunpyBean firstSunpyBean = SpringUtils.getBean(FirstSunpyBean.class);
        resultMap.put("name", firstSunpyBean.getName());
        resultMap.put("age", firstSunpyBean.getAge().toString());
        return resultMap;
    }
}

结果:

image

FactoryBean注册的bean什么时候加载?

AbstractBeanFactory.doGetBean(String name, @Nullable Class requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException方法

image

AbstractBeanFactory.getObjectForBeanInstance方法

image

FactoryBeanRegistrySupport.getObjectFromFactoryBean方法

image

image

posted @ 2023-06-06 22:11  sunpeiyu  阅读(155)  评论(0编辑  收藏  举报