使用springboot+netty+websocket时,在handler层无法进行业务层的service注入,解决办法:
1、编写一个SpringBeanUtils类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringBeansUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringBeansUtils.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return SpringBeansUtils.applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return SpringBeansUtils.applicationContext.getBean(clazz);
}
}
2、在handler层使用时,通过如下方法获得service:
MgtService mgtService = (MgtService)SpringBeansUtils.getBean("mgtServiceImpl");
特别要注意的是:后面getBean()的时候需要写实现类的类名,而不是接口的。