Netty的ServerHandler中注入对象失败

我在使用在Netty的MyUdpHandler中需要调用service的方法,但是在注入service时总是为null

解决方法:

  1.自定义一个工具类实现ApplicationContextAware接口,当一个类实现ApplicationContextAware接口后,当这个类被spring加载后,就能够在这个类中获取到spring的上下文操作符ApplicationContext,通过ApplicationContext 就能够轻松的获取所有的spring管理的bean

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ToolNettySpirngAutowired implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 通过实现ApplicationContextAware接口中的setApplicationContext方法,我们可以获取到spring操作上线文applicationContext变量,
   * 然后把它复制给静态变量applicationContext,这样我们就可以通过MyApplicationContext.applicationContext.getBean()的方式取spring管理的bean。
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ToolNettySpirngAutowired.applicationContext = applicationContext;
    }

    // ps: 获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    // ps: 通过name获取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    // ps: 通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    // ps:通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}

  2.将MyUdpHandler这个先打上@Component注解,交由spring管理

    然后通过工具获取到需要的service对象

   private static DeviceService deviceService;
    private static RtuService rtuService;static {
        deviceService = ToolNettySpirngAutowired.getBean(DeviceServiceImpl.class);
        rtuService = ToolNettySpirngAutowired.getBean(RtuServiceImpl.class);
    }

测试,对象注入成功,成功调用service方法。

原文地址:https://www.cnblogs.com/fansirHome/p/13206656.html