参考博客:https://blog.csdn.net/lida1001/article/details/73913308
一般来说,我们使用springboot都会用@AutoWired自动注入Bean对象,但是有些情况下,@AutoWired无法满足我们,比如线程中,或者动态实例化多个类中的一个对象时。在前段时间做项目时,就遇到这个问题,有多个mybatis的mapper接口,我们需要根据哪个表更新了数据,然后操作对应的mapper获取数据。
下面上代码:
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanId) throws BeansException {
return applicationContext.getBean(beanId);
}
}
代码就不过多的解释,要运行这个代码,你需要在springboot的主方法那里使用回调函数获取上下文对象,这样才能动态注入Bean。
动态注入Bean:
//根据beam名称动态加载bean
MssqlServiceInterface mssqlServiceInterface = (MssqlServiceInterface)SpringContextUtil.getBean(mapperServiceBeanName);
Bean类:
需要在箭头处写上Bean名称,这样才知道你想注入的是什么类。