Java 代码获取Spring容器

由于工作等各样原因,已经很久没有更了,但技术还是不能落的。。。今天抽空记录一个小问题:Java 代码如何获取Spring容器?当然这样的问题百度一搜答案一堆,不过实践出真知,在此记录笔者实际项目中的获取方法。

  1. 首先介绍笔者在项目中获取的方法(整个项目只有一个Spring容器),不废话,直接上代码,
package com.cn.hnust.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil extends ApplicationObjectSupport{
 
    public static ApplicationContext context;
    public static Object getBean(String serviceName){
         return context.getBean(serviceName);
    }
    @Override
    protected void initApplicationContext(ApplicationContext context) throws BeansException {
        super.initApplicationContext(context);
        SpringUtil.context = context;
        //System.out.println("=============================================="+SpringUtil.context+"==============================================");
    }
    
}

如上代码所示,获取ApplicationContext的方法很简单,自己写一个类继承ApplicationObjectSupport 并覆写其initApplicationContext方法,在该方法中将入参的ApplicationContext值赋给本类的静态ApplicationContext类型变量即可,当然 必不可少的操作是,你必须让你写的工具类在Spring容器的管理范围内,即该类需要加上@Component等类似的组建注解,或者将该类配置到xml配置文件,或者将其写入spring配置类中(根据自己的情况自行选择).

2.第二种介绍的方法是,在Spring Web开发环境下,获取ApplicationContext:通过ServletContext来获取ApplicationContext实例,代码如下:

public void init(){  //重写父类
        try {
            super.init();
            ServletContext context=this.getServletContext();
            WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
            queueMessageProducer=(QueueMessageProducer)ctx.getBean("queueMessageProducer");
            receiveDao = (ReceiveDao) ctx.getBean("receiveDao");
        } catch (ServletException e) {
            logger.error("call WebApplicationContext error:"+e);
        }
    }

以上一段代码是一个Servlet的init方法,在该方法中,我们可以通过Spring提供的工具类org.springframework.web.context.support.WebApplicationContextUtilsgetWebApplicationContext(ServletContext)方法来获取ApplicationContext的实例。

3.第三中介绍的是在初始化Spring的时候获取ApplicationContext的引用
在初始化时保存ApplicationContext对象

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

这种方式相信大家都异常熟悉。。。它适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。

你可能感兴趣的:(Java 代码获取Spring容器)