springboot多线程环境下注入bean空指针问题解决

多线程环境下注入bean会出现空指针了..

我是怎么知道这个bean有有没有在启动的时候注入进来的呢?

用于指示 bean 包含在SpringApplication中时应该运行的接口。多个CommandLineRunner bean 可以在同一个应用程序上下文中定义,并且可以使用Ordered接口或@Order注释进行排序。
如果您需要访问ApplicationArguments而不是原始 String 数组,请考虑使用ApplicationRunner 


   @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {

            System.out.println("Let's inspect the beans provided by Spring Boot:");

            String[] beanNames = ctx.getBeanDefinitionNames();
            Arrays.sort(beanNames);
            for (String beanName : beanNames) {
                System.out.println(beanName);
            }

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

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringContextUtil.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 <T>
   * @return
   */
  public static <T> T getBean(Class<T> clazz) {
    return getApplicationContext().getBean(clazz);
  }

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

使用的时候,通过构造器进行注入

 private BlogService blogService;
 
 
     public BlogPageProcessor() {
        this.blogService= SpringContextUtil.getBean(BlogService.class);
    }
posted @ 2022-08-21 17:06  三号小玩家  阅读(824)  评论(0)    收藏  举报
Title
三号小玩家的 Mail: 17612457115@163.com, 联系QQ: 1359720840 微信: QQ1359720840