SpringBoot整合axis1.4后,@Autowired注入失败,使用工具类注入

问题描述:

费劲心思搭建好webservices服务端后,没想到客户端调用失败,查看日志文件,发现报空指针异常,debug代码后,发现sql查询的值都是null。通常情况下,我们将Dao注入Service的时候使用@Autowired注解,但是这里显然没有注入进来。

解决方法:

使用SpringContextUtils工具类注入,首先增加SpringContextUtils.java文件,复制如下内容

 1 import org.springframework.beans.BeansException;
 2 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.ApplicationContextAware;
 5 import org.springframework.stereotype.Component;
 6 /**
 7  * @author xuchi
 8  * @Description: @Autowired注入无效,使用此工具类注入
 9  *
10  */
11 @Component
12 public class SpringContextUtils implements ApplicationContextAware {
13     private static ApplicationContext applicationContext = null;
14 
15     public SpringContextUtils() {
16     }
17 
18     public void setApplicationContext(ApplicationContext arg0) throws BeansException {
19         if (applicationContext == null) {
20             applicationContext = arg0;
21         }
22 
23     }
24 
25     public static ApplicationContext getApplicationContext() {
26         return applicationContext;
27     }
28 
29     public static void setAppCtx(ApplicationContext webAppCtx) {
30         if (webAppCtx != null) {
31             applicationContext = webAppCtx;
32         }
33     }
34 
35     /**
36      * 拿到ApplicationContext对象实例后就可以手动获取Bean的注入实例对象
37      */
38     public static <T> T getBean(Class<T> clazz) {
39         return getApplicationContext().getBean(clazz);
40     }
41 
42     public static <T> T getBean(String name, Class<T> clazz) throws ClassNotFoundException {
43         return getApplicationContext().getBean(name, clazz);
44     }
45 
46     public static final Object getBean(String beanName) {
47         return getApplicationContext().getBean(beanName);
48     }
49 
50     public static final Object getBean(String beanName, String className) throws ClassNotFoundException {
51         Class clz = Class.forName(className);
52         return getApplicationContext().getBean(beanName, clz.getClass());
53     }
54 
55     public static boolean containsBean(String name) {
56         return getApplicationContext().containsBean(name);
57     }
58 
59     public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
60         return getApplicationContext().isSingleton(name);
61     }
62 
63     public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
64         return getApplicationContext().getType(name);
65     }
66 
67     public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
68         return getApplicationContext().getAliases(name);
69     }
70 }

代替以往的

1 @Autowired
2 private ManagerDao managerDao;

而使用

1 ManagerDao managerDao = SpringContextUtils.getBean(ManagerDao.class);

 

上一篇:[第四版]用getaddrinfo设置tcp基本连接属性


下一篇:解决 线程无法使用注入的service类