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容器管理

  • 相关阅读:
    怎么查看keras 或者 tensorflow 正在使用的GPU
    tf.layers.Dense与 tf.layers.dense的区别
    pytorch LSTM 简单形式
    JN_0025:在局域网中调试本地loaclhost项目
    JN_0024:浏览器打开弹窗
    JN_0023:谷歌浏览器启动项设置
    H5_0041:定义方法获取URL参数
    H5_0040:iframe 父子页面方法调用
    H5_0039:iframe 页面嵌套格式 安全选项sandbox
    Web_0008:win系统默认80端口被占用的处理方法
  • 原文地址:https://www.cnblogs.com/zxguan/p/8377429.html
Copyright © 2011-2022 走看看