栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring自定义scope

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring自定义scope

自定义scope创建实例源码: 

注册自定义的scope:使用BeanDefinitionRegistryPostProcessor接口:

package com.spring.postProcessor;

import com.spring.bean.ScopeDemo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class RefreshBeanDefinitionRegistryPostProsser implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        //将自定义的scope注册到spring的scopes容器中
        beanFactory.registerScope("refreshScope",new ScopeDemo());
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {

    }
}

 自定义的scope:必须实现Scope接口

package com.spring.bean;


import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.lang.annotation.Annotation;

public class ScopeDemo  implements Scope {

    @Override
    public Object get(String name, ObjectFactory objectFactory) {
        Object object = objectFactory.getObject();
        return object;
    }

    @Override
    public Object remove(String name) {
        return null;
    }

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

    }

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

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

应用:

package com.spring.bean;

import lombok.Data;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Data
@Scope("refreshScope")//scope的名称,默认single
public class CustomScopeTest {
    private String test;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/859549.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号