问题记录
问题:netty中想要引用Service 发现注入不了 为null
过程:@XxxScan尝试不行 Idea缓存也不行 网上找的@PostConstruct 也不行 后来怀疑是netty的问题 去搜了搜资料
解决:↓ 反正这样可以解决
@Slf4j
@Component
public class CPPHandler extends SimpleChannelInboundHandler<CustomProtocolPacket> implements ApplicationContextAware {
// Spring 容器在初始化该类的时候,会自动将 ApplicationContext 注入进来 有了spring的上下文对象就可以了
private static ApplicationContext applicationContext;
// 这种获取到context对象然后拿bean对象的方式
@Autowired
private AlarmInfoMapper alarmInfoMapper = getBean(AlarmInfoMapper.class);
// xxxxx 业务代码
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
CPPHandler.applicationContext = applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext != null ? applicationContext.getBean(beanName) : null;
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext != null ? applicationContext.getBean(clazz) : null;
}
}
原因:
- netty是独立的网络通信框架,他不是spring容器管理的,所以不能通过·@Autowired/@Resource·注入
- Netty是需要手动管理它的生命周期,启动关闭事件等。spring容器默认管理的单例Bean对象,对于这种主动控制生命周期的,直接给spring有问题。