我在使用在Netty的MyUdpHandler中需要調用service的方法,但是在注入service時總是為null
解決方法:
1.自定義一個工具類實現ApplicationContextAware接口,當一個類實現ApplicationContextAware接口后,當這個類被spring加載后,就能夠在這個類中獲取到spring的上下文操作符ApplicationContext,通過ApplicationContext 就能夠輕松的獲取所有的spring管理的bean
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ToolNettySpirngAutowired implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * 通過實現ApplicationContextAware接口中的setApplicationContext方法,我們可以獲取到spring操作上線文applicationContext變量, * 然后把它復制給靜態變量applicationContext,這樣我們就可以通過MyApplicationContext.applicationContext.getBean()的方式取spring管理的bean。 */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ToolNettySpirngAutowired.applicationContext = applicationContext; } // ps: 獲取applicationContext public static ApplicationContext getApplicationContext() { return applicationContext; } // ps: 通過name獲取 Bean. public static Object getBean(String name) { return getApplicationContext().getBean(name); } // ps: 通過class獲取Bean. public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } // ps:通過name,以及Clazz返回指定的Bean public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }
2.將MyUdpHandler這個先打上@Component注解,交由spring管理
然后通過工具獲取到需要的service對象
private static DeviceService deviceService; private static RtuService rtuService;static { deviceService = ToolNettySpirngAutowired.getBean(DeviceServiceImpl.class); rtuService = ToolNettySpirngAutowired.getBean(RtuServiceImpl.class); }
測試,對象注入成功,成功調用service方法。