当前位置:   article > 正文

SpringBoot线程无法通过@Autowired注入Bean_springboot 线程不能调用@

springboot 线程不能调用@
  1. package com.wis.mes.context;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.ApplicationContextAware;
  5. import org.springframework.stereotype.Component;
  6. /**
  7. * @Author CHENEY
  8. * @Date 2019/03/26
  9. * @Version 1.0
  10. * @Last Modified By : CHENEY
  11. * @Last Modified Time : 2019/03/26
  12. * @Description : bean对象的工具类 (ApplicationContextProvider Service)
  13. * @function:针对多线程无法使用Autowired注入Bean设计
  14. * @Type implements class
  15. * Copyright (c) 2019 WIS Software Co.*
  16. */
  17. @Component
  18. public class ApplicationContextProvider implements ApplicationContextAware {
  19. private static ApplicationContext applicationContext;
  20. @Override
  21. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  22. this.applicationContext = applicationContext;
  23. }
  24. /**
  25. * 获取applicationContext
  26. *
  27. * @return
  28. */
  29. public static ApplicationContext getApplicationContext() {
  30. return applicationContext;
  31. }
  32. /**
  33. * 通过name获取 Bean.
  34. *
  35. * @param name
  36. * @return
  37. */
  38. public static Object getBean(String name) {
  39. return getApplicationContext().getBean(name);
  40. }
  41. /**
  42. * 通过class获取Bean
  43. *
  44. * @param clazz
  45. * @param <T>
  46. * @return
  47. */
  48. public static <T> T getBean(Class<T> clazz) {
  49. return getApplicationContext().getBean(clazz);
  50. }
  51. /**
  52. * 通过name,以及Clazz返回指定的Bean
  53. *
  54. * @param name
  55. * @param clazz
  56. * @param <T>
  57. * @return
  58. */
  59. public static <T> T getBean(String name, Class<T> clazz) {
  60. return getApplicationContext().getBean(name, clazz);
  61. }
  62. }

-------------------------------------------------------- 用法:

DataCoreService dataCoreService = ApplicationContextProvider.getBean(DataCoreService.class);
  1. 注意这里:
  2. @Override
  3. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  4. ApplicationContextProvider.applicationContext = applicationContext;
  5. }
  6. 2、web.xml 添加监听
  7. <listener>
  8. <description>spring监听器</description>
  9. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  10. </listener>
  11. 如果启动时报找不到 applicationContext.xml 添加以下语句
  12. <context-param>
  13. <param-name>contextConfigLocation</param-name>
  14. <param-value>classpath:applicationContext.xml</param-value>
  15. </context-param>
  16. 2、applicationContext.xml 添加以下语句
  17. <bean class="com.zzf.base.ApplicationContextProvider" lazy-init="false"/>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/442009
推荐阅读
相关标签
  

闽ICP备14008679号