springboot获取applicationcontext
使用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的更多相关文章
- SpringBoot项目中获取applicationContext对象
ApplicationContext 对象是Spring开源框架的上下文对象实例,也就是我们常说的Spring容器,一般情况下我们是不用手动来管理它,而是由Spring框架自己来维护bean之间的关系 ...
- springboot获取getBean方法以及ApplicationContext空指针问题解决
创建获取ApplicationContext工具类: package com.performancetest.common.utils; import org.springframework.bean ...
- @PostConstruct +getapplicationcontext.getbean springboot获取getBean
Componentpublic class SpringContextUtils implements ApplicationContextAware { public static Applicat ...
- Spring获取ApplicationContext
在Spring+Struts+Hibernate中,有时需要使用到Spring上下文.项目启动时,会自动根据applicationContext配置文件初始化上下文,可以使用ApplicationCo ...
- 【转】SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法
转自:http://www.coderli.com/junit-spring-test-applicationcontext JUnit单元测试用例中使用Spring框架,直接方式如下. @RunWi ...
- spring获取ApplicationContext对象的方法——ApplicationContextAware
一. 引言 工作之余,在看一下当年学的spring时,感觉我们以前都是通过get~ set~方法去取spring的Ioc取bean,今天就想能不能换种模型呢?因为我们在整合s2sh时,也许有那么一天就 ...
- Spring获取ApplicationContext方式,和读取配置文件获取bean的几种方式
转自:http://chinazhaokeke.blog.163.com/blog/static/109409055201092811354236 Spring获取ApplicationContex ...
- Spring Boot 获取ApplicationContext
package com.demo; import org.springframework.beans.BeansException; import org.springframework.contex ...
- spring mvc在Controller中获取ApplicationContext
spring mvc在Controller中获取ApplicationContext web.xml中进行正常的beans.xml和spring-mvc.xml的配置: 需要在beans.xml中进行 ...
随机推荐
- K8S 高级调度方式
可以使用高级调度分为: 节点选择器: nodeSelector.nodeName 节点亲和性调度: nodeAffinity Pod亲和性调度:PodAffinity Pod反亲和性调度:podAnt ...
- android笔试题二
1.android系统架构: Linux内核——标准库——Framework层——应用层 Linux层包括:Android系统的核心服务,硬件驱动,进程管理,系统安全等等 (现在又加了一层变成了:Li ...
- Markdown介绍及工具推荐
什么是Markdown? Markdown是一种可以使用普通文本编辑器编写的标记语言,通过简单的标记语法,它可以使普通文本内容具有一定的格式.百度百科markdown 还没听说过Markdown?那赶 ...
- 简单 PHP + MySQL 数据库动态网站制作 -- 摘抄
在这篇文章中,我尽量用最浅显易懂的语言来说明使用 PHP, MySQL 制作一个动态网站的基本技术.阅读本文需要简单的 HTML 基础知识和(任一编程语言的)编程基础知识(例如变量.值.循环.语句块的 ...
- weblogic报错----Received exception while creating connection for pool "TDMSKD": The Network Adapter could not establish the connection
<2017-8-16 上午08时58分37秒 CST> <Info> <WebLogicServer> <BEA-000377> <Startin ...
- C#核心基础--类的继承
继承 一个类可以继承自另一个类.在 C#中,类与类之间只存在单一继承.也就是说,一个类的直接基类只能有一个.当类与类之间实现继承的时候,子类可以将它的直接基类的所有成员当做自己的成员,除了类的静态构造 ...
- Django + Uwsgi + Nginx 实现生产环境部署
本节内容 uwsgi 介绍 uwsgi安装使用 nginx安装配置 django with nginx 如何在生产上部署Django? Django的部署可以有很多方式,采用nginx+uwsgi的方 ...
- Linux进程优先级的处理--Linux进程的管理与调度(二十二)
1. linux优先级的表示 1.1 优先级的内核表示 linux优先级概述 在用户空间通过nice命令设置进程的静态优先级, 这在内部会调用nice系统调用, 进程的nice值在-20~+19之间. ...
- shell read变量的读入
shell变量的输入: shell变量除了可以直接赋值或脚本传参外,还可以使用read命令从标准输入获取,read为bash内置命令,可以通过help read查看帮助. 语法格式: read [参数 ...
- vbs脚本,电脑说出指定内容
新建文件, 输入一下脚本, 然后保存文件为 .vbs 文件, 双击脚本, 电脑就能听到电脑发出 你好 的声音 CreateObject("SAPI.SpVoice").Speak& ...