Best Practise of injecting applicationContext in Spring3

后端 未结 5 1601
陌清茗
陌清茗 2020-12-14 12:09

As in the title above, I am confused about pros cons between injecting applicationContext by directly @Autowired annnotation or implementing ApplicationContextAware interfac

5条回答
  •  醉酒成梦
    2020-12-14 12:47

    There is no need to use ApplicationContext at all.

    ObjectFactory

    If you need to use prototype scoped beans in a singleton bean, inject an org.springframework.beans.factory.ObjectFactory. For example using constructor injection:

    @Service
    class MyClass {
        private ObjectFactory myDependencyFactory;
    
        public MyClass(ObjectFactory prototypeFactory) {
            myDependencyFactory = prototypeFactory;
        }
    
    }
    

    Why

    Now what's the benefit over using ApplicationContext ? You can substitute this dependency (e.g. in a test) by simply passing a lambda (since ObjectFactory is a @FunctionalInterface) that returns a stubbed version of it.

    While it is possible to stub the ApplicationContext, it is not clear in that case which beans will be looked up and need to be stubbed.

提交回复
热议问题