美文网首页
springboot获取ApplicationContext的几

springboot获取ApplicationContext的几

作者: 套马杆的程序员 | 来源:发表于2021-01-07 15:29 被阅读0次

工具类

package com.yzj.learn.common.utils;
 
 
import org.springframework.context.ApplicationContext;
 
public class SpringContextUtil {
 
    private static ApplicationContext applicationContext;
 
    public static void setApplicationContext(ApplicationContext context){
 
        applicationContext=context;
    }
 
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
 
    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }
 
    public static Object getBean(Class<?> requiredType){
        return applicationContext.getBean(requiredType);
    }
 
 
}

第一种写法

@SpringBootApplication
public class ServiceCommonApplication {
 
    public static void main(String[] args) {
 
       SpringContextUtil.setApplicationContext( SpringApplication.run(ServiceCommonApplication.class, args));
    }
 
}

第二种写法

package com.yzj.learn.common.listeners;
 
import com.yzj.learn.common.utils.SpringContextUtil;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.*;
 
public class ContexListener implements ApplicationListener<ApplicationContextEvent> {
 
 
    @Override
    public void onApplicationEvent(ApplicationContextEvent event) {
 
        if (event instanceof ContextRefreshedEvent) {
            SpringContextUtil.setApplicationContext(event.getApplicationContext());
            System.out.println("context 刷新");
        }
 
        if (event instanceof ContextClosedEvent) {
            System.out.println("context 关闭");
        }
 
        if (event instanceof ContextStoppedEvent) {
 
            System.out.println("context 停止");
        }
 
        if (event instanceof ContextStartedEvent) {
 
            System.out.println("Context 开启");
        }
 
    }
}
 
@SpringBootApplication
public class ServiceCommonApplication {
 
    public static void main(String[] args) {
 
        SpringApplication springApplication=new SpringApplication(ServiceCommonApplication.class);
        springApplication.addListeners(new ContexListener());
        springApplication.run(args);
    }
 
}

第三种写法直接注入

@Autowired
ApplicationContext app;

相关文章

网友评论

      本文标题:springboot获取ApplicationContext的几

      本文链接:https://www.haomeiwen.com/subject/dppzoktx.html