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();
                }
           } 
        }
    }
  • 相关阅读:
    FocusScope学习三: 对FocusScope 的探究与总结
    FocusScope学习二: 很好的理解FocusScope的工作原理
    不同XML之间节点的拷贝
    计算几何DotVector
    计算几何Graham法凸包
    计算几何UVa10652
    线性筛三合一,强大O(n)
    计算几何AngRadVector
    线性筛euler,强大O(n)
    矩阵bzoj1898
  • 原文地址:https://www.cnblogs.com/guoyinli/p/7152517.html
Copyright © 2011-2022 走看看