最近在做一个聊天室的课设,之前一直都只接触web开发,第一次接触服务器开发,接触到Netty,但在Netty的Handler类里注入为null。
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Autowired
private UserRepository userRepository;
....
}
userRepository注入后为nul,在上寻求了多种方法,参考了一些大神的博文,Spring Boot非controller使用@Autowired注解注入为null的问题(加@Component注解,再写个初始化函数),依旧无效。
最后,参考/s648667069/p/的方法
写了个SpringUtil工具类,代码如下:
import ;
import ;
import ;
import ;
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if( == null) {
= applicationContext;
}
}
//获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过name获取 Bean.
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
Handler代码修改为:
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private static UserRepository userRepository;
static {
userRepository = ();
}
...
}
成功注入!