Spring Bean的获取方法 (手动注入bean)超级实用

本文介绍了如何在Spring框架中使用SpringJobBeanFactory实现ApplicationContextAware接口,以便在初始化阶段获取ApplicationContext。在处理MQTT消息时,展示了如何手动注入Bean并进行数据保存操作。

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

常用的地方:

比如:初始化方法调用数据库的方法中,这时候操作数据库的(bean 容器)方法还没有创建好。

方法如下:

package com.example.mqtt_mode.mqtt.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author IT空门_门主
 * @date 2024/1/5
 */
@Component
public class SpringJobBeanFactory implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringJobBeanFactory.applicationContext=applicationContext;

    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        if (applicationContext == null){
            return null;
        }
        return (T)applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T>  name) throws BeansException {
        if (applicationContext == null){
            return null;
        }
        return applicationContext.getBean(name);
    }

}

运用场景:

  /**
     * 处理要保存的数据
     */
    public  void saveDate(MqttMessage mqttMessage){
        log.info("线程执行中");
        log.info("-----处理要保存的数据-----");
        if (new String(mqttMessage.getPayload()).equals("offline")){
            log.info("消息内容为空");
            return ;
        }
        Map bean = JSONUtil.toBean(new String(mqttMessage.getPayload()), Map.class);
        Test1 test1 = new Test1();
        test1.setUserName(bean.get("userName").toString());
        test1.setAge(Integer.parseInt(bean.get("age").toString()));
        log.info("结果:{}", bean.get("userName"));
        log.info("结果:{}", bean.get("age"));
        //手动注入 Bean  //SpringJobBeanFactory
        Test1Service test1Mapper = SpringJobBeanFactory.getBean(Test1Service.class);
        test1Mapper.save(test1);

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT空门:门主

你的鼓励是我发稿的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值