springboot获取applicationcontext

时间:2022-03-01 12:07:17

使用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方法中启动类代码

springboot获取applicationcontext

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

springboot获取applicationcontext

查看ConfigurableApplicationContext

springboot获取applicationcontext

接口实现了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. Spring获取ApplicationContext

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

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

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

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

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

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

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

  7. Spring Boot 获取ApplicationContext

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

  8. spring mvc在Controller中获取ApplicationContext

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

  9. spring 代码中获取ApplicationContext&lpar;&commat;AutoWired&comma;ApplicationListener&rpar;

    2017年度全网原创IT博主评选活动投票:http://www.itbang.me/goVote/234    学习spring框架时间不长,一点一滴都得亲力亲为.今天忽然觉得老是通过@Autowir ...

随机推荐

  1. MFC连接ftp服务器

    CInternetSession* m_pInetSession; CFtpConnection*   m_pFtpConnection; //连接服务器的函数 BOOL CftpClientDlg: ...

  2. ThinkPHP 整合 PHPExcel ,数据导出功能实现,解决Invalid cell coordinate

    PHPExcel想必大家都不陌生,是用来操作Office Excel 文档的一个PHP类库,它基于微软的OpenXML标准和PHP语言.可以使用它来读取.写入不同格式的电子表格 本次只做数据导出功能的 ...

  3. 反射&plus;自定义注解---实现Excel数据列属性和JavaBean属性的自动映射

    简单粗暴,直奔主题.   需求:通过自定义注解和反射技术,将Excel文件中的数据自动映射到pojo类中,最终返回一个List<pojo>集合? 今天我只是通过一位使用者的身份来给各位分享 ...

  4. Python——函数,模块,简单文件读写

    函数(function)定义原则: 最大化代码重用,最小化代码冗余,流程符合思维逻辑,少用递归; 函数的定义方法: def function_name(param_1, param_2): ..... ...

  5. 使用Idea初始化SpringMvc项目

    (1) (2) (3) (4) (5)感谢http://www.cnblogs.com/feiyujun/p/6537510.html (6)

  6. P1384 幸运数与排列

    P1384 幸运数与排列 神奇的(逆)康托展开:求1到n的全排列中字典序第k小的排列 $k<=10^9<13!$,显然$k$最多只会影响后$13$位 前面一大串都是有序从小到大排列的,于是 ...

  7. 20155333 《网络对抗》 Exp5 MSF基础应用

    20155333 <网络对抗> Exp5 MSF基础应用 基础问题回答 用自己的话解释什么是exploit,payload,encode exploit:攻击手段,是能使攻击武器(payl ...

  8. Codeforces Round &num;272 &lpar;Div&period; 2&rpar; E&period; Dreamoon and Strings 动态规划

    E. Dreamoon and Strings 题目连接: http://www.codeforces.com/contest/476/problem/E Description Dreamoon h ...

  9. Android 网络教程&colon; 开始

    原文:Android Networking Tutorial: Getting Started 作者:Eunice Obugyei 译者:kmyhy 从 API 级别 1 开始,网络始终是 Andro ...

  10. IOS渠道追踪方式

    本文来自网易云社区 作者:马军 IOS,安卓渠道追踪的差异 Google Play国内不可用,国内的安卓 App 分发,都是依托几十个不同的应用市场或发行渠道,如百度.360.腾讯等互联网企业以及小米 ...