zoukankan      html  css  js  c++  java
  • 线程中调用service 处理具体的业务

      线程中调用service 处理具体的业务,在多线程时使用@Autowired总是获取不到bean,原因是:new thread不在spring容器中,也就无法获得spring中的bean对象。

      线程入口,直接写个main方法执行的,运行则获取不到service。需要在 SpringBootApplication 中启动。

       

    /******************************************* BeanContext 类 *******************/
    /*************************************用静态方法直接取的容器中的spring对象*****************/
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;

    @Component
    public class BeanContext implements ApplicationContextAware {

    // Spring应用上下文环境
    private static ApplicationContext applicationContext;

    /*
    * 实现了ApplicationContextAware 接口,必须实现该方法;
    * 通过传递applicationContext参数初始化成员变量applicationContext
    */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    BeanContext.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
    return applicationContext;
    }

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

    public static <T> T getBean(Class<T> clz) throws BeansException {
    return (T)applicationContext.getBean(clz);
    }
    }
    /******************************************* TestHandler 类 *******************/
     

    
    

      

  • 相关阅读:
    Go 笔记之如何防止 goroutine 泄露
    调试 Go 的代码生成
    使用k8s容器钩子触发事件
    springboot教程
    Intellij IDEA 使用Spring-boot-devTools无效解决办法
    c# WMI获取机器硬件信息(硬盘,cpu,内存等)
    各式 Web 前端開發工具整理
    Informix 中执行多条SQL(Execute Script)
    Log4Net
    mysql 按年度、季度、月度、周、日SQL统计查询
  • 原文地址:https://www.cnblogs.com/bianchengxia/p/9240376.html
Copyright © 2011-2022 走看看