小猴子先生

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

在启用线程中使用来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();
            }
       } 
    }
}

 

posted on 2017-07-11 20:38  小猴子先生  阅读(965)  评论(0编辑  收藏  举报