이유:
netty가 시작될 때 NettyServerHandler가 새롭고 호스팅을 위해 스프링 IOC로 넘겨지지 않기 때문에 주입 된 빈은 netty에서 사용할 수 없습니다.
방법 1 :
객체를 생성 할 때 특정 초기화 작업을 완료하고 싶고 이러한 초기화 작업은 주입 된 빈에 따라 다르므로 @PostConstruct를 사용하여 초기화를 완료하는 init 메서드에 주석을 달 수 있습니다. 초기화는 빈 주입이 완료된 후 자동으로 호출됩니다. .
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
@Autowired
private RedisService redisService;
private static NettyServerHandler nettyServerHandler;
@PostConstruct
public void init() {
nettyServerHandler = this;
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
nettyServerHandler.redisService.getString()
}
//。。。。。。。。。以下部分省略
}
방법 2 :
도구 클래스를 사용하여 필요한 빈을 얻고, 스프링 컨테이너 외부의 클래스에서 빈 메서드를 호출하고, NettyOperate nettyOperate = SpringUtils.getBean (NettyOperate.class);
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 获取StringBean必须要加入到容器中
*/
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* 重写父类方法
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtils.applicationContext == null){
SpringUtils.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
}