Springboot如何获取上下文ApplicationContext

目录
  • Springboot获取上下文ApplicationContext
  • springboot的应用上下文
    • ServletWebServerApplicationContext
    • 扩展的功能
    • AnnotationConfigServletWebServerApplicationContext

Springboot获取上下文ApplicationContext

在项目中遇到了一个场景,就是通过获得上下文然后获取特定的bean。在此遇到了不小的坑,故留下这个篇文章,做个记录。

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

@Component
public class SpringContextUtil implements ApplicationContextAware {
    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.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类型的静态变量,但是由于静态变量是不能被Spring容器管理的,一开始用正常的getter和setter方法不能获取到特定的bean,实践证明,需要在此变量的setter方法上加上@Autowired注解,并且去除setter方法中的static关键字。才可实现特定bean的注入。

springboot的应用上下文

springboot上下文有两个

  • ServletWebServerApplicationContext
  • AnnotationConfigServletWebServerApplicationContext(继承上面)

ServletWebServerApplicationContext

该类属于spring-boot-2.1.1Release.jar中,是自springboot诞生就衍生出来的,是spring框架的应用上下文Application的子类。

多说无益,show me code

扩展的功能

首先让我们来看一下,这个类到底做了什么,有什么存在的价值?

    private volatile WebServer webServer;
 @Override
 protected void onRefresh() {
  super.onRefresh();
  try {
   createWebServer();
  }
  catch (Throwable ex) {
   throw new ApplicationContextException("Unable to start web server", ex);
  }
 }

在此类中有个WebServer成员变量,让我们用脚趾头想一下也应该可以知道,这其实就是web服务对象,也基本上可以猜测就是跟tomcat相关了(当然也可以是其他web服务器,如jetty)

然后我们又发现了onRefresh方法,相信我们并不陌生,这就是spring核心refresh方法的中一个钩子方法(即表明此时已经加载所有配置bean),进行WebServer对象的创建

 @Override
 protected void finishRefresh() {
  super.finishRefresh();
  WebServer webServer = startWebServer();
  if (webServer != null) {
   publishEvent(new ServletWebServerInitializedEvent(webServer, this));
  }
 }

我们又发现该类存在finishRefresh,仔细想一下,这个也是spring核心#refresh方法中的一个钩子方法(不过这个特别,因为该方法是refresh方法中的最后一步,即会去实例化spring容器中的所有beandefinition对象)

首先赞一个,这个很巧妙,调用了super.finishRefresh() ,并没有丢弃父类的逻辑功能(这点在多态中,我相信还是会有人犯错,本来是扩展功能,但是直接重写,丢弃了父类的方法,当然spring框架开发大佬肯定不会犯这种错误,对吧!)

第二点重点来了,就是startWebServer,也就是在spring完成实例化之后,就会去启动web服务。

AnnotationConfigServletWebServerApplicationContext

小结一下:

首先此类是springboot启动运行run()创建ApplicationContext的实现类,不过很可惜,该类并没有很强的实质性扩展。

**唯一作用就是拥有了通过注解加载配置类的作用,即和AnnotationConfigApplication一样,只不过springboot的运行启动已经是通过注解加载bean类**

(虽然是鸡肋,不过这也符合spring创建类的一贯风格,就是每个类都是高内聚的,即每个类除了父类的功能之外,还都拥有其他扩展的作用。即使创建出来还没有用到就被遗弃,但仍然不能阻止spring开发大佬创建该类,哈哈)

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

(0)

相关推荐

  • Springboot 如何获取上下文对象

    目录 Springboot上下文对象获取 或者更简单的写法: spring boot获取上下文 随时取出被spring管理的bean对象 方法一: 方式二: Springboot上下文对象获取 package it.benjamin.aspirinweb.mem; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.sp

  • 详解在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的上下文环境ApplicationContext的最简单方式

    目录 获取Spring上下文环境ApplicationContext 分析: 正确的做法是: 注意: Spring上下文(ApplicationContext)理解 什么是Spring应用上下文呢??? 通过.class文件获取bean的方法: 获取Spring上下文环境ApplicationContext Web项目中发现有人如此获得Spring的上下环境: public class SpringUtil { public static ApplicationContext context =

  • 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如何获取上下文ApplicationContext

    目录 Springboot获取上下文ApplicationContext springboot的应用上下文 ServletWebServerApplicationContext 扩展的功能 AnnotationConfigServletWebServerApplicationContext Springboot获取上下文ApplicationContext 在项目中遇到了一个场景,就是通过获得上下文然后获取特定的bean.在此遇到了不小的坑,故留下这个篇文章,做个记录. import org.s

  • 关于Springboot如何获取IOC容器

    目录 Springboot项目中获取IOC容器的方式 方法一(不实用,不推荐): 方法二(强烈推荐): 总结 Springboot项目中获取IOC容器的方式 在Springboot项目中如果要获取IOC容器目前有两种方法. 方法一(不实用,不推荐): 在Springboot项目中都会存在一个SpringApplication的启动类,我们通过以下代码启动IOC容器. SpringApplication.run(Application.class, args); 其实run方法会将创建的IOC容器

  • 详解SpringBoot静态方法获取bean的三种方式

    目录 方式一  注解@PostConstruct 方式二  启动类ApplicationContext 方式三 手动注入ApplicationContext 方式一  注解@PostConstruct import com.example.javautilsproject.service.AutoMethodDemoService; import org.springframework.beans.factory.annotation.Autowired; import org.springfr

  • SpringBoot中获取profile的方法详解

    目录 spring boot与profile 静态获取方式 autowire ProfileConfig spring boot与profile spring boot 的项目中不再使用xml的方式进行配置,并且,它还遵循着约定大于配置. 静态获取方式 静态工具类获取当前项目的profile环境. import org.springframework.beans.BeansException; import org.springframework.context.ApplicationConte

  • JS中用EL表达式获取上下文参数值的方法

    1. action返回参数到页面 /** * 测试js中获取后台传值 * @param model * @param req * @return String */ @RequestMapping("getValue") public String getValue(Model model, HttpServletRequest req){ model.addAttribute("stringValue", "测试在js中取值..."); mod

  • springboot如何获取相对路径文件夹下静态资源的方法

    今日遇到一个问题:springboot需要获取到一个自定义名称文件夹下的静态资源(图片等),并且文件夹的路径不在classPath下面,而是一个相对路径. 一开始使用修改配置文件的方式: # 配置静态资源访问前缀 spring.mvc.static-path-pattern=*/** # 配置静态资源路径,默认配置失效 spring.resources.static-locations=../upload 发现并不行,无法解析出相对路径. 后面通过自定义静态资源映射配置类实现了: @Config

  • Springboot @Value获取值为空问题解决方案

    这篇文章主要介绍了Springboot @Value获取值为空问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在spring中,常常使用 @Value("${property}") 从application.properties中取值,需要注意两点 使用 @Value 的类不能使用 new 关键字进行实例化对象,必须采用 依赖注入的方式进行实例化 不能使用显式的构造方法 否则,将取不到值.解决方法如下: 删除显式的构造方法

  • springboot项目获取resources相对路径的方法

    springboot文件上传保存到resources里,用 System.getProperty("user.dir");参数即可获得项目相对路径.(ps:不知道是不是springboot内嵌tomcat容器的原因,用网上的request.getServletContext().getRealPath("/")方法获得的路径不是项目路径,而是c盘下一个tomcat目录路径) 保存成功图: 到此这篇关于springboot项目获取resources相对路径的方法 的文

  • Springboot如何获取配置文件application.yml中自定义的变量并使用

    前言:在写项目中我们经常要将同样的变量在不同的文件中写无数次,这样修改起来要一通好找,非常不方便,平常都会写一个工具类存入自己的变量进行调用取值,但是呢,懒得写咋办,写了还要注入,注入失败又得.........麻烦,有没有办法写在配置文件中直接自定义变量通过注解的方式取值呢?肯定有啊. 正文: 一.在application.yml中配置自己的变量比如: person: name: '张三' age: '年龄25' home: '拥有房子1套' car: '轿车1辆' 二.使用注解取值并且使用 i

随机推荐