request scoped beans in spring testing

后端 未结 8 922
自闭症患者
自闭症患者 2020-11-30 00:54

I would like to make use of request scoped beans in my app. I use JUnit4 for testing. If I try to create one in a test like this:

@RunWith(SpringJUnit4Clas         


        
8条回答
  •  清歌不尽
    2020-11-30 01:27

    Test Request-Scoped Beans with Spring explains very well how to register and create a custom scope with Spring.

    In a nutshell, as Ido Cohn explained, it's enough to add the following to the text context configuration:

    
        
            
                
                    
                
            
        
    
    

    Instead of using the predefined SimpleThreadScope, based on ThreadLocal, it's also easy to implement a Custom one, as explained in the article.

    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.beans.factory.ObjectFactory;
    import org.springframework.beans.factory.config.Scope;
    
    public class CustomScope implements Scope {
    
        private final Map beanMap = new HashMap();
    
        public Object get(String name, ObjectFactory factory) {
            Object bean = beanMap.get(name);
            if (null == bean) {
                bean = factory.getObject();
                beanMap.put(name, bean);
            }
            return bean;
        }
    
        public String getConversationId() {
            // not needed
            return null;
        }
    
        public void registerDestructionCallback(String arg0, Runnable arg1) {
            // not needed
        }
    
        public Object remove(String obj) {
            return beanMap.remove(obj);
        }
    
        public Object resolveContextualObject(String arg0) {
            // not needed
            return null;
        }
    }
    

提交回复
热议问题