基于Spring上下文工具类 ApplicationContextUtil

目录
  • Spring上下文工具类 ApplicationContextUtil
  • 获取ApplicationContext的工具类
    • 方式一
    • 方式二
    • 方式三
    • 方式四
    • 方式五

Spring上下文工具类 ApplicationContextUtil

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * spring 上下文工具类
 * @author DAWN
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

获取ApplicationContext的工具类

在项目中,经常遇到这样的问题:

有些类需要使用new来创建对象,但是类中需要使用spring容器中定义的bean,此时无法通过spring的自动注入来注入我们需要使用的bean。

所以需要手动的从spring容器中获取bean。要获取bean必须先获取到ApplicationContext对象,有以下方式可以获取该对象。

方式一

手动创建ApplicationContext对象,并保存起来。

public class ApplicationContextUtil {
    private static ApplicationContext context;
    static {
        context = new ClassPathXmlApplicationContext("applicationContext.xml");
    }
    public static ApplicationContext getApplicationContext() {
        return context;
    }
}

方式二

在web环境中通过spring提供的工具类获取,需要ServletContext对象作为参数。然后才通过ApplicationContext对象获取bean。

下面两个工具方式的区别是,前者在获取失败时返回null,后者抛出异常。

另外,由于spring是容器的对象放在ServletContext中的,所以可以直接在ServletContext取出 WebApplicationContext 对象。

ApplicationContext context1 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ApplicationContext context2 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

方式三

工具类继承抽象类ApplicationObjectSupport,并在工具类上使用@Component交由spring管理。

这样spring容器在启动的时候,会通过父类 ApplicationObjectSupport中的setApplicationContext()方法将ApplicationContext对象设置进去。

可以通过getApplicationContext()得到ApplicationContext对象。

方式四

工具类继承抽象类WebApplicationObjectSupport,查看源码可知WebApplicationObjectSupport是继承了ApplicationObjectSupport,所以获取ApplicationContext对象的方式和上面一样,也是使用getApplicationContext()方法。

方式五

工具类实现ApplicationContextAware接口,并重写setApplicationContext(ApplicationContext applicationContext)方法,在工具类中使用@Component注解让spring进行管理。

spring容器在启动的时候,会调用setApplicationContext()方法将ApplicationContext 对象设置进去。

@Component
public class ApplicationContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    public static ApplicationContext getApplicationContext() {
        return context;
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Spring获取ApplicationContext对象工具类的实现方法

     Spring获取ApplicationContext对象工具类的实现方法 (1)实现的工具类: package com.util; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; final public class ApplicationContextUtil { private s

  • spring中通过ApplicationContext getBean获取注入对象的方法实例

    用SpringContextUtil实现ApplicationContextAware package util; import java.util.Locale; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; pub

  • SpringBoot获取ApplicationContext的3种方式

    ApplicationContext是什么? 简单来说就是Spring中的容器,可以用来获取容器中的各种bean组件,注册监听事件,加载资源文件等功能. Application Context获取的几种方式 1 直接使用Autowired注入 @Component public class Book1 { @Autowired private ApplicationContext applicationContext; public void show (){ System.out.printl

  • 详解在SpringBoot应用中获取应用上下文方法

    1.定义上下文工具类: package com.alimama.config; import org.springframework.context.ApplicationContext; /** * 上下文获取工具类 * @author mengfeiyang * */ public class SpringContextUtil { private static ApplicationContext applicationContext; public static void setAppl

  • 基于Spring上下文工具类 ApplicationContextUtil

    目录 Spring上下文工具类 ApplicationContextUtil 获取ApplicationContext的工具类 方式一 方式二 方式三 方式四 方式五 Spring上下文工具类 ApplicationContextUtil import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework

  • Spring通过工具类实现获取容器中的Bean

    目录 1. Aware 接口 2. BeanFactoryAware 3. TienChin 项目实践 1. Aware 接口 小伙伴们知道,Spring 容器最大的特点在于所有的 Bean 对于 Spring 容器的存在是没有意识的,因此我们常说理论上你可以无缝将 Spring 容器切换为其他容器(然而在现实世界中,我们其实没有这样的选择,除了 Spring 容器,难道还有更好用的?). 当然这只是一个理论,在实际开发中,我们往往要用到 Spring 容器为我们提供的诸多资源,例如想要获取到容

  • 基于spring三方包类注入容器的四种方式小结

    如果引用第三方jar包,肯定是不能直接使用常用注解@Controller.@Service.@Repository.@Component将类的实例注入到spring容器中.以下四种方法可以向spring容器中导入三方包中类实例 . 1 xml配置 这种情况大家用的比较多,就是在spring的xml文件中配置需要导入的bean.在springweb项目工程web.xml中 ContextLoaderListener或者DispatcherServlet的初始参数contextConfigLocat

  • Spring boot工具类静态属性注入及多环境配置详解

    由于需要访问MongoDB,但是本地开发环境不能直接连接MongoDB,需要通过SecureCRT使用127.0.0.2本地IP代理.但是程序部署到线上生产环境后,是可以直接访问MongoDB的,因此开发好程序后,总是要修改一下MongoDB服务器的IP才能提交代码,这样很是不方便. private static final String PUBCHAT_HOST = "127.0.0.2"; // private static final String PUBCHAT_HOST =

  • Spring Utils工具类常用方法实例

    Spring提供的工具类,主要用于框架内部使用,这个类提供了一些简单的方法,并且提供了易于使用的方法在分割字符串,如CSV字符串,以及集合和数组. StringUtils提供常用的方法如下: 判断对象对象是否为null或者空字符串 public static boolean isEmpty(@Nullable Object str) { return (str == null || "".equals(str)); } 判断给的序列是否为空或者length为0 public stati

  • 简单了解Spring中常用工具类

    文件资源操作 Spring 定义了一个 org.springframework.core.io.Resource 接口,Resource 接口是为了统一各种类型不同的资源而定义的,Spring 提供了若干 Resource 接口的实现类,这些实现类可以轻松地加载不同类型的底层资源,并提供了获取文件名.URL 地址以及资源内容的操作方法 访问文件资源 * 通过 FileSystemResource 以文件系统绝对路径的方式进行访问: * 通过 ClassPathResource 以类路径的方式进行

  • 详解Spring中BeanUtils工具类的使用

    目录 简介 Spring的BeanUtils方法 Spring的BeanUtils与Apache的BeanUtils区别 实例 简介 说明 本文介绍Spring的BeanUtils工具类的用法. 我们经常需要将不同的两个对象实例进行属性复制,比如将DO对象进行属性复制到DTO,这种转换最原始的方式就是手动编写大量的 get/set代码,很繁琐.为了解决这一痛点,就诞生了一些方便的类库,常用的有 Apache的 BeanUtils,Spring的 BeanUtils, Dozer,Orika等拷贝

  • Spring @Cacheable注解类内部调用失效的解决方案

    目录 @Cacheable注解类内部调用失效 @Cacheable注解缓存方法内部调用 方法一 方法二 方法三 方法四 @Cacheable注解类内部调用失效 如果你只是想使用一个轻量级的缓存方案,那么可以尝试使用Spring cache方案. 那么在使用spring @Cacheable注解的时候,要注意,如果类A的方法f()被标注了@Cacheable注解,那么当类A的其他方法,例如:f2(),去直接调用f()的时候,@Cacheable是不起作用的,原因是@Cacheable是基于spri

  • Spring常用一些工具类实例汇总

    一.内置Resource类型 org.springframework.core.io.UrlResource org.springframework.core.io.ClassPathResource:以类路径的方式进行访问 org.springframework.core.io.FileSystemResource:以文件系统绝对路径的方式进行访问 org.springframework.web.context.support.ServletContextResource:以相对于 Web 应

随机推荐