spring默认情况下管理的类是singleton模式,如果在类A中注入了B类,但是B类属于non-singleton,每次使用A的时候都需要初始化B类。
spring提供了ApplicationContextAware,让A意识到spring容器的存在,并且在调用B类的时候通过容器去询问B类是否是单例模式,需要重新初始化?
// a class that uses a stateful Command-style class to perform some processing package fiona.apple; // Spring-API imports import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class CommandManager implements ApplicationContextAware { private ApplicationContext applicationContext; public Object process(Map commandState) { // grab a new instance of the appropriate Command Command command = createCommand(); // set the state on the (hopefully brand new) Command instance command.setState(commandState); return command.execute(); } protected Command createCommand() { // notice the Spring API dependency! return this.applicationContext.getBean("command", Command.class); } public void setApplicationContext( ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
主要在这里: return this.applicationContext.getBean("command", Command.class);去检测B是否需要重新初始化