最近在做项目中的Socket通信的时候,同时要获取数据里的数据,但是在Socket的线程却没法通过注解的方式获取(一些thread类或servlet不能通过spring注解的方式调用spring容器里面的类),我解决的方法是通过实现ApplicationContextAware接口
public class SpringUtil implements ApplicationContextAware{ private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{ SpringUtil.applicationContext = applicationContext; } }
Spring配置如下:
<bean id="applicationContext" class="com.ncjk.utcs.common.servlet.SpringUtil"> </bean>
通过下面的方法就能获取到Spring里的类了
SignalControlerService signalControlerService = (SignalControlerService) SpringUtil.getApplicationContext().getBean("signalControlerService",SignalControlerService.class);或者SignalControlerService signalControlerService = (SignalControlerService) SpringUtil.getApplicationContext().
getBean("signalControlerService");
SignalControlerService类使用注解
@Service("signalControlerService") public class SignalControlerService implements ISignalControlerService { @Resource private ICommonDAO commonDAO; /*省略后续代码*/ }