zoukankan      html  css  js  c++  java
  • 解决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();
                }
           } 
        }
    }
  • 相关阅读:
    web.py的input获取问题
    python unicode和 utf8字符串比较
    python default encoding
    linux flash player的问题
    centos 支持 ntfs格式
    学习jqueryjquery中的show()和hide()
    字符串等长分割
    类加载器分类
    类加载器子系统
    70道HR的面试题
  • 原文地址:https://www.cnblogs.com/guoyinli/p/7152517.html
Copyright © 2011-2022 走看看