spring -- 自定义 scope

必须 实现 scope 接口

public class CustomScope implements Scope {

    ThreadLocal<Object> threadLocal = new ThreadLocal<>();
    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {

        Object object = objectFactory.getObject();
        threadLocal.set(object);
        return object;
    }

    @Override
    public Object remove(String name) {
        Object o = threadLocal.get();
        threadLocal.remove();
        return o;
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {

    }

    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }
}

注册 scope


@Component
public class ScopeRegister implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {

    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        beanFactory.registerScope("cusScope",new CustomScope());
    }
}

使用

@Component
@Scope("cusScope")
public class BeanDemo {
    private String name ="jack";
}

 

测试

public class ZTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:application.xml");
        Object beanDemo = applicationContext.getBean("beanDemo");
        System.out.println(beanDemo);
    }
}

 

源码简单描述

执行 第一行代码后 ,applicationContext 还没有 BeanDemo 的实例 , 再new ClassPathXmlApplicationContext 之后 ,只有非抽象类 ,单例 ,非懒加载的才会 实例化 

源码在 DefaultListableBeanFactory.java 的 preInstantiateSingletons 方法中

 

 

 

执行第二行代码 。直接 允许 AbstractBeanFactory 的 doGetBean 方法

 

 

 调用 scope.get方法,实际上是 调用我们自定义的方法(CustomScope 重写的方法),  而自定义方法中 Object object = objectFactory.getObject(); 实际上是调用上面的 lambda 表达式,创建对象。

 

我们的对象最终    没有保存在beanFactory中,而是保存在我们自己定义的ThreadLocal中(具体要放在哪里,完全可以自定义)

posted on 2021-03-03 22:08  xingshouzhan  阅读(371)  评论(0编辑  收藏  举报

导航