the reason:
The injected bean cannot be used in netty, because NettyServerHandler is new when netty is started, and it is not handed over to spring IOC for hosting
method 1:
You want to complete certain initialization operations when you generate the object, and these initialization operations depend on the injected bean, so you can use @PostConstruct to annotate an init method to complete the initialization, which will be automatically called after the bean injection is completed.
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()
}
//。。。。。。。。。以下部分省略
}
Method 2:
Use the tool class to obtain the required bean, call the bean method in the class outside the spring container, and place 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);
}
}