使用springboot之前,我们通过ClassPathXmlApplicationContext加载spring xml配置文件来获取applicationcontext,使用springboot后,由于不存在xml文件,故该种方式已经不能使用

在官方文档中介绍,可通过实现ApplicationRunner或者CommandLineRunner在springaplication启动后,立即执行其中的一些代码,做初始化操作,如果存在多个实现类,可使用@Order注解设置其启动顺序,也可使用实现ApplicationListener来做初始化操作,并且实现ApplicationListener可获取到applicationcontext

获取applicationcontext的方式有多种,以下列举出两种方式

一、实现ApplicationListener<ContextRefreshedEvent>

1、启动类

package com.demo.bootdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import com.demo.bootdemo.listeners.MainBusiListeners;
import com.demo.bootdemo.test.TestBean;
import com.demo.bootdemo.uitils.ApplicationContextUtils; @SpringBootApplication
public class MydemoApplication { public static void main(String[] args) {
SpringApplication sa = new SpringApplication(MydemoApplication.class);
sa.addListeners(new MainBusiListeners());
sa.run(args);
// 测试
TestBean bean = ApplicationContextUtils.getBean(TestBean.class);
bean.print("yes it is test.");
} }

2、启动监听

package com.demo.bootdemo.listeners;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import com.demo.bootdemo.uitils.ApplicationContextUtils; /**
* 启动监听
*/
public class MainBusiListeners implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContextUtils.setContext(event.getApplicationContext());
}
}

3、ApplicationContext工具类

package com.demo.bootdemo.uitils;

import org.springframework.context.ApplicationContext;

/**
* ApplicaitonContext工具类
*
*/
public class ApplicationContextUtils { private static ApplicationContext context; public static void setContext(ApplicationContext applicationContext) {
context = applicationContext;
} public static Object getBean(String beanName) {
return context.getBean(beanName);
} public static <T> T getBean(Class<T> t) {
return context.getBean(t);
}
}

4、测试Bean

package com.demo.bootdemo.test;

import org.springframework.stereotype.Component;

/**
* 测试Bean
*/
@Component
public class TestBean { public void print(String str) {
System.out.println("input: " + str);
}
}

5、启动启动类MydemoApplication.java

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE) 2019-04-04 09:51:28.722 INFO 93344 --- [ main] com.demo.bootdemo.MydemoApplication : Starting MydemoApplication on admin-PC with PID 93344 (D:\Programs\eclipseworkplace\springboot\mydemo\target\classes started by admin in D:\Programs\eclipseworkplace\springboot\mydemo)
2019-04-04 09:51:28.725 INFO 93344 --- [ main] com.demo.bootdemo.MydemoApplication : No active profile set, falling back to default profiles: default
2019-04-04 09:51:29.247 INFO 93344 --- [ main] com.demo.bootdemo.MydemoApplication : Started MydemoApplication in 0.838 seconds (JVM running for 1.204)
input: yes it is test.

通过上述输出结果可知,applicationcontext正常获取,如果需要在run方法执行之前,使用applicationcontext做一些事情,可在MainBusiListeners的onApplicationEvent方法中进行。另外,使用@Component或者具有类似功能注解,启动类中去掉sa.addListeners(new MainBusiListeners());,一样可以正常获取applicationcontext,ApplicationListener中的Event有多种,父接口为ApplicationEvent,具体可参考源码查看

二、启动类run方法返回值即为applicationcontext

查看main方法中启动类代码

查看run方法,发现该方法返回ConfigurableApplicationContext

查看ConfigurableApplicationContext

接口实现了ApplicaitonContext接口,所以run方法返回的值就是我们需要的context了

启动类

package com.demo.Demo001;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication
public class App {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
ContextUtils.setApplicationContext(context);
MainBusiEntry.execute();
}
}

context工具类

package com.demo.Demo001;

import org.springframework.context.ApplicationContext;

public class ContextUtils {

    public static ApplicationContext context;

    private ContextUtils() {
} public static void setApplicationContext(ApplicationContext applicationContext) {
context = applicationContext;
} public static Object getBean(String beanName) {
return context.getBean(beanName);
} public static <T> T getBean(Class<T> t) {
return context.getBean(t);
}
}

测试bean

package com.demo.Demo001;

import org.springframework.stereotype.Component;

@Component
public class TestBean {
public String getName() {
return this.getClass().getCanonicalName();
}
}

业务处理入口

package com.demo.Demo001;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; public class MainBusiEntry { private static Logger logger = LogManager.getLogger(MainBusiEntry.class);
public static void execute() {
TestBean bean = ContextUtils.getBean(TestBean.class);
logger.info(bean.getName());
}
}

启动springboot,输出结果如下

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.0.RELEASE) 11:53:25.302 INFO org.springframework.boot.StartupInfoLogger.logStarting()/50 - Starting App on admin-PC with PID 195640 (D:\Programs\eclipseworkplace\springboot\Demo001\target\classes started by admin in D:\Programs\eclipseworkplace\springboot\Demo001)
11:53:25.338 INFO org.springframework.boot.SpringApplication.logStartupProfileInfo()/675 - No active profile set, falling back to default profiles: default
11:53:26.375 INFO com.mongodb.diagnostics.logging.SLF4JLogger.info()/71 - Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
11:53:26.456 INFO org.springframework.boot.StartupInfoLogger.logStarted()/59 - Started App in 1.393 seconds (JVM running for 2.078)
11:53:26.459 INFO com.demo.Demo001.MainBusiEntry.execute()/11 - com.demo.Demo001.TestBean

输出了测试类的路径。

我们在开发中,使用的为第一种获取applicationcontext的方式

springboot获取applicationcontext的更多相关文章

  1. SpringBoot项目中获取applicationContext对象

    ApplicationContext 对象是Spring开源框架的上下文对象实例,也就是我们常说的Spring容器,一般情况下我们是不用手动来管理它,而是由Spring框架自己来维护bean之间的关系 ...

  2. springboot获取getBean方法以及ApplicationContext空指针问题解决

    创建获取ApplicationContext工具类: package com.performancetest.common.utils; import org.springframework.bean ...

  3. @PostConstruct +getapplicationcontext.getbean springboot获取getBean

    Componentpublic class SpringContextUtils implements ApplicationContextAware { public static Applicat ...

  4. Spring获取ApplicationContext

    在Spring+Struts+Hibernate中,有时需要使用到Spring上下文.项目启动时,会自动根据applicationContext配置文件初始化上下文,可以使用ApplicationCo ...

  5. 【转】SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法

    转自:http://www.coderli.com/junit-spring-test-applicationcontext JUnit单元测试用例中使用Spring框架,直接方式如下. @RunWi ...

  6. spring获取ApplicationContext对象的方法——ApplicationContextAware

    一. 引言 工作之余,在看一下当年学的spring时,感觉我们以前都是通过get~ set~方法去取spring的Ioc取bean,今天就想能不能换种模型呢?因为我们在整合s2sh时,也许有那么一天就 ...

  7. Spring获取ApplicationContext方式,和读取配置文件获取bean的几种方式

    转自:http://chinazhaokeke.blog.163.com/blog/static/109409055201092811354236  Spring获取ApplicationContex ...

  8. Spring Boot 获取ApplicationContext

    package com.demo; import org.springframework.beans.BeansException; import org.springframework.contex ...

  9. spring mvc在Controller中获取ApplicationContext

    spring mvc在Controller中获取ApplicationContext web.xml中进行正常的beans.xml和spring-mvc.xml的配置: 需要在beans.xml中进行 ...

随机推荐

  1. SpringBoot项目打war包部署Tomcat教程

    一.简介 正常来说SpringBoot项目就直接用jar包来启动,使用它内部的tomcat实现微服务,但有些时候可能有部署到外部tomcat的需求,本教程就讲解一下如何操作 二.修改pom.xml 将 ...

  2. 如何用ABP框架快速完成项目(10) - ABP只要加人即可马上加快项目进展- 全栈篇(1) - 发挥DDD理论优势的时候到了!

    正如我在<程序员英语二三事(2) - 从听开始>里说的, 任何技术/工具/语言都有其适用场景和上下文环境. DDD理论同样是如此.   现在, 终于到了发挥DDD理论优势的时候啦!   一 ...

  3. 对YUV数据进行裁剪

    项目中用到,用来对YUV数据(图片的yuv或者视频单帧yuv数据)进行裁剪. 格式介绍:http://blog.csdn.net/vblittleboy/article/details/1094514 ...

  4. html之css选择器学习

    相关内容: 什么是css选择器 标签选择器 类选择器 id选择器 并集选择器(分组选择器) 交集选择器 后代选择器 子标签选择器 属性选择器 相邻兄弟选择器 伪类选择器 伪元素选择器(伪对象选择器) ...

  5. coTurn 使用测试方法

    做个记录 1.从"../examples/etc/" 目录拷贝turnserver.conf文件到"/usr/local/etc/"目录 2.修改配置文件 主要 ...

  6. SQL Server中sys.syslogin中updatedate字段的浅析

    在系统视图sys.syslogins中,有createdate与updatedate两个字段,分别表示创建登录名与更新登录名的日期,如果你用updatedate的值来判断一个登录名的权限是否被修改过, ...

  7. Docker & pure-ftpd 快速加建 FTP 服务器

    项目需要进行升级服务,现在需要基于centos 7使用docker来快速打架一个FTP环境来方便本地文件上传. 本次使用的是 pure-ftpd docker镜像,有关镜像使用的详细信息,本人是从 h ...

  8. 2018(2017)美图java服务端笔试(回忆录)

    选择题有几道,是比较基础的 填空题两道:一道是类似c语言的给出abc的值求 ++a+b+++c++  ,另一道是说出两个常见的垃圾回收算法 编程题 找出出现次数为1的数字然后改进(要求O(n)) 数据 ...

  9. 动态Linq表达式生成

    动态构建 WHERE(C=>C.Id=Value): public static IQueryable<T> WhereEqual<T>(this IQueryable& ...

  10. memory 监控 mysql vs percona vs maria

    oracle mysql 5.7 在performance_schema 通过以下表展现内存信息.这些表实际engine为performance_schema.这些表数据实际是以数组的形式存储在内存中 ...