Spring获取Bean( 不完美) @Service@Lazy(false)public class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext = null; private static final Logger log = LoggerFact
@Service @Lazy(false) public class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext = null; private static final Logger log = LoggerFactory.getLogger(SpringContextHolder.class); /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */ public staticT getBean(Class requiredType) { return applicationContext.getBean(requiredType); } public static T getBean(String id) { return (T) applicationContext.getBean(id); } public static Map getBeans(Class var1) { return applicationContext.getBeansWithAnnotation(var1); } @Override public void destroy() throws Exception { if (log.isDebugEnabled()) { log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext); } applicationContext = null; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // logger.debug("注入ApplicationContext到SpringContextHolder:{}" + applicationContext); // if (SpringContextHolder.applicationContext != null) { // logger.info("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext); // } this.applicationContext = applicationContext; // NOSONAR }