-
创建工具类
/**
- spring容器的相关方法,如根据名称获取spring实例
- @author 天真热
- @create 2022-04-28 9:55
- @desc
**/
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;@Component
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtils.applicationContext = applicationContext; } public static Object getBean(String name) { return applicationContext.getBean(name); } public static <T> T getBean(Class<T> requiredType) { return applicationContext.getBean(requiredType); } public static <T> T getBean(String name, Class<T> requiredType) { return applicationContext.getBean(name, requiredType); } public static boolean containsBean(String name) { return applicationContext.containsBean(name); } public static boolean isSingleton(String name) { return applicationContext.isSingleton(name); } public static Class<? extends Object> getType(String name) { return applicationContext.getType(name); }
}
2.调用
ps:正常我们不指定类注入到spring的名称,默认都是使用"首字母小写的类名"作为名称
TaskRunKafkaLogService taskRunKafkaLogService = (TaskRunKafkaLogService) SpringContextUtils.getBean("taskRunKafkaLogServiceImpl");