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

posted @ 2018-01-30 09:59  ^梦幻星空^  阅读(1155)  评论(0编辑  收藏  举报