优雅获取ApplicationContext上下文对象,ApplicationContextUtil上下文获取工具类
提示:以下是本篇文章正文内容,下面案例可供参考
一、实现接口实现ApplicationContextAware接口获取上下文对象
package com.example.demo.config;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static <T> T getBean(String beanName) {
return (T)applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> className) {
return applicationContext.getBean(className);
}
}
二、SpringBoot启动类setApplicationContext获取上下文对象
①SpringBoot启动类
package com.example.demo;
import com.example.demo.config.ApplicationContextUtil2;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
//设置上下文工具类中对象
ApplicationContextUtil2.setApplicationContext(applicationContext);
}
}
②ApplicationContext应用上下文帮助类
package com.example.demo.config;
import org.springframework.context.ApplicationContext;
public class ApplicationContextUtil2 {
private static ApplicationContext applicationContext;
public static void setApplicationContext(ApplicationContext context) {
applicationContext = context;
}
public static <T> T getBean(String beanName) {
return (T)applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> className) {
return applicationContext.getBean(className);
}
}