Springboot实现多线程注入bean的工具类操作代码示例

作者:袖梨 2020-08-26

本篇文章小编给大家分享一下Springboot实现多线程注入bean的工具类操作代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

场景: 使用springboot多线程,线程类无法自动注入需要的bean

解决方法:通过工具类获取需要的bean

工具类代码:

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

/**
 * @Description: 获取bean对象的工具类
 * @Author: Zhang Lin
 * @CreateDate: 2018/12/10
 */

@Component
public class ApplicationContextProvider implements ApplicationContextAware {
  /**
   * 上下文对象实例
   */
  private static ApplicationContext applicationContext;

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

  /**
   * 获取applicationContext
   *
   * @return
   */
  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }

  /**
   * 通过name获取 Bean.
   *
   * @param name
   * @return
   */
  public static Object getBean(String name) {
    return getApplicationContext().getBean(name);
  }

  /**
   * 通过class获取Bean.
   *
   * @param clazz
   * @param 
   * @return
   */
  public static  T getBean(Class clazz) {
    return getApplicationContext().getBean(clazz);
  }

  /**
   * 通过name,以及Clazz返回指定的Bean
   *
   * @param name
   * @param clazz
   * @param 
   * @return
   */
  public static  T getBean(String name, Class clazz) {
    return getApplicationContext().getBean(name, clazz);
  }
}

使用方法:

在线程类的构造函数里调用工具类的getBeans方法获取实例,如:

public class ThreadA implements Runnable {
  private Service service;
  public ThreadA() {
    this.service = ApplicationContextProvider.getBean(Service.class);
  }

  @Override
  public void run() {
  //TO BE DONE
  }
}

相关文章

精彩推荐