当前位置:   article > 正文

springboot获取ApplicationContext的几种方式_springboot getapplicationcontext().getparent()

springboot getapplicationcontext().getparent()

工具类

  1. package com.yzj.learn.common.utils;
  2. import org.springframework.context.ApplicationContext;
  3. public class SpringContextUtil {
  4. private static ApplicationContext applicationContext;
  5. public static void setApplicationContext(ApplicationContext context){
  6. applicationContext=context;
  7. }
  8. public static ApplicationContext getApplicationContext() {
  9. return applicationContext;
  10. }
  11. public static Object getBean(String name){
  12. return applicationContext.getBean(name);
  13. }
  14. public static Object getBean(Class<?> requiredType){
  15. return applicationContext.getBean(requiredType);
  16. }
  17. }

第一种写法

  1. @SpringBootApplication
  2. public class ServiceCommonApplication {
  3. public static void main(String[] args) {
  4. SpringContextUtil.setApplicationContext( SpringApplication.run(ServiceCommonApplication.class, args));
  5. }
  6. }

第二种写法

  1. package com.yzj.learn.common.listeners;
  2. import com.yzj.learn.common.utils.SpringContextUtil;
  3. import org.springframework.context.ApplicationListener;
  4. import org.springframework.context.event.*;
  5. public class ContexListener implements ApplicationListener<ApplicationContextEvent> {
  6. @Override
  7. public void onApplicationEvent(ApplicationContextEvent event) {
  8. if (event instanceof ContextRefreshedEvent) {
  9. SpringContextUtil.setApplicationContext(event.getApplicationContext());
  10. System.out.println("context 刷新");
  11. }
  12. if (event instanceof ContextClosedEvent) {
  13. System.out.println("context 关闭");
  14. }
  15. if (event instanceof ContextStoppedEvent) {
  16. System.out.println("context 停止");
  17. }
  18. if (event instanceof ContextStartedEvent) {
  19. System.out.println("Context 开启");
  20. }
  21. }
  22. }
  1. @SpringBootApplication
  2. public class ServiceCommonApplication {
  3. public static void main(String[] args) {
  4. SpringApplication springApplication=new SpringApplication(ServiceCommonApplication.class);
  5. springApplication.addListeners(new ContexListener());
  6. springApplication.run(args);
  7. }
  8. }

第三种写法直接注入

  1. @Autowired
  2. ApplicationContext app;

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/66326
推荐阅读
相关标签
  

闽ICP备14008679号