部分一转载自:http://blog.csdn.net/yang123111/article/details/32099329

via @yang123111

部分二转载自:http://www.cnblogs.com/20160813main/p/5826446.html

via @Chell

获取Spring的上下文环境ApplicationContext的方式

Web项目中发现有人如此获得spring的上下环境:

public class SpringUtil {

       public static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 
       public static Object getBean(String serviceName){
             return context.getBean(serviceName);
       }
}

在web项目中这种方式非常不可取!!!

分析:

首先,主要意图就是获得Spring上下文;

其次,有了Spring上下文,希望通过getBean()方法获得Spring管理的Bean的对象;

最后,为了方便调用,把上下文定义为static变量或者getBean方法定义为static方法;

但是,在web项目中,系统一旦启动,web服务器会初始化Spring的上下文的,我们可以很优雅的获得Spring的ApplicationContext对象。

如果使用

new ClassPathXmlApplicationContext("applicationContext.xml");
相当于重新初始化一遍!!!!

也就是说,重复做启动时候的初始化工作,第一次执行该类的时候会非常耗时!!!!!

正确的做法是:

@Component
public class SpringContextUtil implements ApplicationContextAware {

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

         /*

          * 实现了ApplicationContextAware 接口,必须实现该方法;

          *通过传递applicationContext参数初始化成员变量applicationContext

          */

         public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
               SpringContextUtil.applicationContext = applicationContext;
         }

 

         public static ApplicationContext getApplicationContext() {
                return applicationContext;
         }

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

}

 

注意:这个地方使用了Spring的注解@Component,如果不是使用annotation的方式,而是使用xml的方式管理Bean,记得写入配置文件

<bean id="springContextUtil" class="com.ecdatainfo.util.SpringContextUtil" singleton="true" />

 

其实

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
这种方式获取Sping上下文环境,最主要是在测试环境中使用,比如写一个测试类,系统不启动的情况下手动初始化Spring上下文再获取对象!

*******************************************************************************************************************************************

如果想要在run()方法中调用dao层或者service层,常规的方法应该是这样

    public class ServerStatusWatcherThread extends Thread {

      

      @Resource(name="servermanageDao") 
      ServerManagementMapper servermanageDao;

      @Autowired
      ServerManagementService serverservice;

      @Override

      public void run(){

          List<ServerManagementItem> servers =servermanageDao.getAll();

          

          serverservice.QuerySOSServer();

          //what do you want to do please write here

      }

    }

    结果会报如下异常:Exception in thread "Thread-3" java.lang.NullPointerException

解决方法可以用getBean的方式来解决这个问题,异常解决

  

    public class ServerStatusWatcherThread extends Thread {

      

      //@Resource(name="servermanageDao") 
      //ServerManagementMapper servermanageDao;

      //改成

      ServerManagementMapper  servermanageDao=(ServerManagementMapper) SpringContextUtil.getBean("servermanageDao");

      //@Autowired
      //ServerManagementService serverservice;

      //改成:

      ServerManagementService servemanagementService=(ServerManagementService) SpringContextUtil.getBean("servemanagementService");

      @Override

      public void run(){

          List<ServerManagementItem> servers =servermanageDao.getAll();

          

          serverservice.QuerySOSServer();

          //what do you want to do please write here

      }

    }

Java Spring 在线程中或其他位置获取 ApplicationContext 或 ServiceBean的更多相关文章

  1. 解决 spring boot 线程中使用@Autowired注入Bean的方法,报java.lang.NullPointerException异常

    问题描述 在开发中,因某些业务逻辑执行时间太长,我们常使用线程来实现.常规服务实现类中,使用 @Autowired 来注入Bean,来调用其中的方法.但如果在线程类中使用@Autowired注入的Be ...

  2. 一文搞懂Java/Spring/Dubbo框架中的SPI机制

    几天前和一位前辈聊起了Spring技术,大佬突然说了SPI,作为一个熟练使用Spring的民工,心中一紧,咱也不敢说不懂,而是在聊完之后赶紧打开了浏览器,开始的学习之路,所以也就有了这篇文章.废话不多 ...

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

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

  4. 通过spring,在项目的任意位置获取当前Request

    需要引入: import javax.servlet.http.HttpServletRequest; import org.springframework.web.context.request.R ...

  5. Java核心知识点 --- 线程中如何创建锁和使用锁 Lock , 设计一个缓存系统

    理论知识很枯燥,但这些都是基本功,学完可能会忘,但等用的时候,会发觉之前的学习是非常有意义的,学习线程就是这样子的. 1.如何创建锁? Lock lock = new ReentrantLock(); ...

  6. java android 将 List中元素互换位置

    很多时候我要对List中的元素调换位置,这时候可以用如下代码,意思是将data中的index1与index2元素互换位置 //data 为List Collections.swap(data,inde ...

  7. Java在不同线程中运行代码

    start()方法开始为一个线程分配CPU时间,这导致对run()方法的调用. 代码1 package Threads; /** * Created by Frank */ public class ...

  8. spring mvc Controller中使用@Value无法获取属性值

    在使用spring mvc时,实际上是两个spring容器: 1,dispatcher-servlet.xml 是一个,我们的controller就在这里,所以这个里面也需要注入属性文件 org.sp ...

  9. shell 字符串中定位字符位置 获取字符位置

    linux shell 字符串操作(长度,查找,替换)详解 该博文中描述的如下两个字符串操作, ${string:position} #在$string中, 从位置$position开始提取子串 ${ ...

随机推荐

  1. 不校验csrf

    from django.views.decorators.csrf import csrf_exempt@csrf_exemptdef a(request): pass

  2. Elasticsearch .net client NEST 空字符/null值查询

    null值查询 当某个字段值为null时,其实在es里该条数据是没有这个字段的.查询时检测包含不包含该字段就行. /// <summary> /// null 值查询 /// 当数据为Nu ...

  3. C# Post 参数中的特殊符号处理

    https://cloud.tencent.com/developer/article/1344673 http://blog.csdn.net/henulwj/article/details/791 ...

  4. VWmare设置挂载目录

     [root@localhost ~]# mkdir -p /mnt/cdrom  #首先创建一个挂载目录 [root@localhost ~]# mount -t auto /dev/cdrom / ...

  5. oracle 11g RAC 的基本操作(一)------启动与关闭

    启动RAC 手工启动按照HAS, cluster, database的顺序启动,具体命令如下: 启动HAS(High Availability Services),必须以root用户 [root@or ...

  6. vue数据变动监测

    原文链接:https://blog.csdn.net/man_tutu/article/details/72148362 对象: 不能监测到: var vm = new Vue({ data:{ a: ...

  7. 微信小程序外包 就找北京动软 专业承接微信小程序定制

    很多人问为什么要开发微信小程序,微信小程序的“入口”在哪儿? 1.只有访问过的小程序,才会出现所谓的「入口」. 所有访问过得小程序都可以从微信首屏下面的「发现」点过去.(必须是最新版微信) 这个所谓的 ...

  8. python内置函数详细描述与实例演示

    python有许多内置函数,列出表格如下 内置函数 abs() delattr() hash() memoryview() set() all() dict() help() min() setatt ...

  9. Android测试(二)——adb常用命令

    连接设备: 安装应用包apk文件: adb install apk文件 卸载应用: adb uninstall 包名 将设备中的文件放到本地: adb pull 设备文件目录 本地文件目录 将本地文件 ...

  10. Eggjs 设置跨域请求

    1. 安装egg-cors npm install egg-cors --save 2.打开config/plugin.js exports.cors: { enable: true, package ...