当前位置 : 主页 > 编程语言 > java >

java----Spring系列

来源:互联网 收集:自由互联 发布时间:2021-06-28
Spring获取Bean( 不完美) @Service@Lazy(false)public class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext = null; private static final Logger log = LoggerFact
Spring获取Bean( 不完美)
@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 static 
 
   T 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 }
    
   
  
 
网友评论