zoukankan      html  css  js  c++  java
  • Spring 自定义Bean 实例获取

     一、通过指定配置文件获取, 对于Web程序而言,我们启动spring容器是通过在web.xml文件中配置,这样相当于加载了两次spring容器

    ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
    ac.getBean("beanId"); 

    二、通过Spring提供的工具类获取ApplicationContext对象

    ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
    ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
    MyService service1 = (MyService)ac1.getBean("bean1");//这是beanId. 
    MyService service2 = (MyService)ac2.getBean("bean2");

      这种方式明显有很大的漏洞,其一:需要request对象,其二:很难封装一个Java工具类

    三、实现接口ApplicationContextAware, 或继承实现ApplicationContextAware接口的类

    package com.zxguan;
    
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ApplicationObjectSupport;
    
    /**
     * @author zxguan
     * @description
     * @create 2018-01-29 14:54
     */
    public class SpringTool extends ApplicationObjectSupport {
    
        private static ApplicationContext applicationContext = null;
    
        @Override
        protected void initApplicationContext(ApplicationContext context) throws BeansException {
            super.initApplicationContext(context);
            if (null == SpringTool.applicationContext) {
                SpringTool.applicationContext = context;
            }
        }
    
        public static ApplicationContext getAppContext() {
            return applicationContext;
        }
    
        public static Object getBean(String beanId){
            return getAppContext().getBean(beanId);
        }
    }

      还需将类 SpringTool 交由 Spring容器管理

  • 相关阅读:
    在Android工程中运行Java程序问题
    sklearn.neighbors.kneighbors_graph的简单属性介绍
    python中的“.T”操作
    numpy中关于*和dot的区别
    一个Window Service引发的感想
    项目管理之初步认识
    由敏捷开发中开发认领自己的工作内容的感想
    SQL Server2008 inner join多种方式的实践
    浅谈业务逻辑和技术哪个更重要
    敏捷人生之初步认识
  • 原文地址:https://www.cnblogs.com/zxguan/p/8377429.html
Copyright © 2011-2022 走看看