解决Spring在线程中注入为空指针的问题

在启用线程中使用来jdbcTemplate来查询数据库,引入jdbcTemplate是用Spring  @Autowired注解  方式引入,但是在运行中 jdbcTemplate 总是 空指针

解决方法:

定义一个静态获取Bean的类

@Component
public class SpringUtils implements ApplicationContextAware{  
    //Spring应用上下文环境
    private static ApplicationContext applicationContext;  
    /**
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
     */
    public void setApplicationContext(ApplicationContext applicationContext)  
            throws BeansException {  
        this.applicationContext = applicationContext;  
    }  
  
    public static ApplicationContext getApplicationContext(){  
        return applicationContext;  
    }  
      /**
     * 获取对象 这里重写了bean方法,起主要作用
     */
    public static Object getBean(String name) throws BeansException{  
        return applicationContext.getBean(name);  
    }  
}

线程类这样写:

public class MyTread extends Thread{
        //不要使用 @Autowired
    private JdbcTemplate jdbcTemplate;
    public void run()  
    {  
        this.jdbcTemplate=  SpringUtils.getApplicationContext().getBean(JdbcTemplate.class); 
       while(true){
            ArrayList res = (ArrayList).this.jdbcTemplate.queryForList("写自己的sql语句");
            //延时功能
            try {
                //延时两秒
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
       } 
    }
}
原文地址:https://www.cnblogs.com/guoyinli/p/7152517.html