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

常用的地方:

比如:初始化方法调用数据库的方法中,这时候操作数据库的(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 getBean(String name) throws BeansException {
        if (applicationContext == null){
            return null;
        }
        return (T)applicationContext.getBean(name);
    }

    public static  T getBean(Class  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);

    }

你可能感兴趣的:(spring,oracle,java)