其中一个方法参考于:https://blog.csdn.net/ziany/article/details/78845433
最近在开发的时候,遇见了一个问题,Spring的配置文件和Struts2的配置文件无法注入Service,虽然已知是因为线程无法注入Service,但是一直没有很好的解决方法,虽然用过几种常见的用法,但并不能有效的使用,当今天无意间看见这个博文的时候,试了一下,果然好使,以此记录我的三种使用方式----------仅适用于在工具类里无法注入Service的情况(包括因线程run()方法引起的无法注入)
第一种:(需要多次加载配置文件,若配置文件要跑很长的方法,慎用)利用Application Context,再次使用一次配置文件:Service用例写为 XXXService
ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
IXXXService xxxService = (IXXXService) ac.getBean("xxxService");
xxxService.addXXX();
其中getBean的字符串为配置文件内<bean>的id
<bean id="xxxService" class="xxx.xxx.impl.xxxService" />
第二种:(比较鸡肋且白痴,但不用多次加载配置文件)在各个使用到的位置,注入Service后使用
第三种:(重头戏,既不用多次加载配置文件,也不用写很多方法,也是今天所学到的【再次声明参考地址】https://blog.csdn.net/ziany/article/details/78845433)
首先,创建一个工具类,SpringContextUtil,其内容在参考博文中有,在此为了自己加深印象,再打一遍。。。
public class SpringContextUtil implements ApplicationContextAware { //注意是ApplicationContextAware
private static ApplicationContext context = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{
this.context = applicationContext;
}
public static <T> T getBean(String beanName){
return (T) context.getBean(beanName);
}
public static String getMessage(String key){
return context.getMessage(key,null,Locale.getDefault());
}
}
第二步,将这个方法注入到applicationContext(或者主配置文件 -common)
<bean id="SpringContextUtil" class="xxx.xxx.xxx.SpringContextUtil" />
第三步,将service写入到配置文件中,
<bean id="xxxService" class="xxx.xxx.impl.xxxService" />
第四步,在无法注入的类里面,声明Service
private IXXXService xxxService;
第五步,在想要使用Service的地方使用,但是前提需要走一下配置
xxxService = SpringContextUtil.getBean("xxxService"); /*此一步可以配置在线程开始的方法里,也可以放在run()方法里(我反正没放在run()类里)详细一点可以参考https://blog.csdn.net/ziany/article/details/78845433,比较直观*/
xxxService.addXXX();
完结-----撒花