Spring框架學習--自定義Scope類型


1.首先需要定義一個Scope借口的實現類,至少需要實現get和remove方法:

/**
 * Created by feiyu on 16/9/13.
 */
public class ThreadScope implements Scope {

    private final ThreadLocal<Map<String, Object>> threadScope = new ThreadLocal<Map<String, Object>>(){
        @Override
        protected Map<String, Object> initialValue() {
            return new HashMap<String,Object>();
        }
    };


    public Object get(String name, ObjectFactory<?> objectFactory) {
        Map<String,Object> scope = threadScope.get();
        Object obj = scope.get(name);
        if(obj == null){
            obj = objectFactory.getObject();
            scope.put(name, obj);
        }
        return obj;
    }


    public Object remove(String name) {
        Map<String,Object> scope = threadScope.get();
        return scope.remove(name);
    }

    public void registerDestructionCallback(String name, Runnable callback) {

    }

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

    public String getConversationId() {
        return null;
    }

2.注冊Scope

Scope threadScope = new ThreadScope();
beanFactory.registerScope("thread", threadScope);

  

3.使用Scope

<bean id=".." class=".." scope="thread"/>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM