工具类
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;
网友评论