zoukankan      html  css  js  c++  java
  • spring-从普通java类取得注入spring Ioc容器的对象的方案

    1.启动服务时通过spring容器的监听器(继承ContextLoaderListener 监听器的方法)

    public class ListenerSpringContext extends ContextLoaderListener {
        private final Logger log = LoggerFactory.getLogger(ListenerSpringContext.class);
    
        public void contextInitialized(ServletContextEvent event) {
            log.info("init ListenerSpringContext...");
            super.contextInitialized(event);
            ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
         //自己手动保留一个spring注入的容器
            UtilsSpringContext.setApplicationContext(applicationContext);
        }
    
    }

    2.实现appctionContextaware的方法

    package com.ceopen.eoss.spring;  
      
    import org.springframework.beans.BeansException;  
    import org.springframework.context.ApplicationContext;  
    import org.springframework.context.ApplicationContextAware;  
      
    public class SpringUtil implements ApplicationContextAware {  
          
        private static ApplicationContext applicationContext;  
          
        @Override  
        public void setApplicationContext(ApplicationContext context)  
            throws BeansException {  
            SpringUtil.applicationContext = context;  
        }  
        public static Object getBean(String name){  
            return applicationContext.getBean(name);  
        }  
    }  

     将SpringUtil注入spring配置文件

    <bean id="spring" class="com.ceopen.eoss.spring.SpringUtil" />  

    获取

    ICBMission icbMission = (ICBMission)SpringUtil.getBean("ICBMission");  
  • 相关阅读:
    练习2
    练习1
    如何生成添加前缀的顺序DIV
    mysql5.7 版本中 timestamp 不能为零日期 以及sql_mode合理设置
    MIME类型大全
    Intel Xeon E5-2620 v4参数
    webgl开发中添加IIS的mime类型
    jquery.validate动态更改校验规则
    mvc4
    asp.net防SQL/JS注入攻击:过滤标记
  • 原文地址:https://www.cnblogs.com/hwaggLee/p/5462527.html
Copyright © 2011-2022 走看看