首页 > 技术文章 > listener@Autowired无法注入bean的一种解决方法

xiaolibiji 2022-01-19 14:11 原文

public class FileListener extends FileAlterationListenerAdaptor {
 
    @Autowired
    private WebSocketConfig webSocketConfig;
}

上述代码中 webSocketConfig的值一直为null;

原因:listener、fitter都不是Spring容器管理的,无法在这些类中直接使用Spring注解的方式来注入我们需要的对象。

解决方法1:从spring的上下文WebApplicationContext 中获取,最直接的。

解决方法2:根据自己项目需要,修改初始化参数。

步骤1:将要注入的bean作为listener的属性处理,并生成set和get方法

@Component
public class FileListener implements FileAlterationListener {
    private static WebSocketConfig webSocketConfig;

    public static WebSocketConfig getWebSocketConfig() {
        return webSocketConfig;
    }

    public static void setWebSocketConfig(WebSocketConfig webSocketConfig) {
        FileListener.webSocketConfig = webSocketConfig;
    }
}

步骤2: 编写初始化类,在初始化类中对listener进行赋值。(实际业务需要初始化类,仅供吐槽)

@Component
@Order(value = 1)
public class FileInitRun implements CommandLineRunner {

    @Autowired
    private WebSocketConfig webSocketConfig;

    @Override
    public void run(String... args) throws Exception {
        //解决listener注入不了spring容器对象的问题
        FileListener.setWebSocketConfig(webSocketConfig);
    }
}

经过这样处理,可以在FileListener对locationService对象进行操作了。

原文链接:https://blog.csdn.net/qq_40823910/article/details/90439040

推荐阅读