java学习——springboot动态获得javaBean,手动注入Bean

本文介绍了一种在SpringBoot中动态注入Bean的方法,通过自定义SpringContextUtil工具类实现。适用于线程或动态实例化场景,如根据不同表更新操作对应的Mybatis mapper。通过在主方法中使用回调函数获取ApplicationContext,实现动态加载Bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考博客:https://blog.youkuaiyun.com/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名称,这样才知道你想注入的是什么类。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值