zy2019
V2EX  ›  Java

new 的线程导入无法通过 @Autowired 注入

  •  
  •   zy2019 · Jun 27, 2019 · 4349 views
    This topic created in 2708 days ago, the information mentioned may be changed or developed.

    项目 spring boot + gradle + netty,

    我在项目启动时创建了这么一个线程: new UdpServerThread(8000).start(); 直接启动 netty 的服务器

    然后这个作为服务器接收客户端信息在 protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) 中接收信息

    接收到信息后,会把收到的数据传给方法 A

    方法 A 中会通过 @Autowired DataCache dataCache; 去调用缓存

    现在的话就一直在调用 dataCache 时报空指针

    大概查了下,问题可能出现 new 的线程不在 spring 容器中,但查到的解决办法不是很好,所以想问下,一般这个改怎么解决呢?

    10 replies  •  2019-06-27 18:27:48 +08:00
    hfc
    hfc
    Jun 27, 2019
    1
    UdpServerThread 类中加一个成员变量,再通过 set 方法赋值
    anakinsky
    anakinsky
    Jun 27, 2019
    2
    封装个 SpringBeanUtils,beanFactory.getBean(beanName);
    guoyuchuan
    guoyuchuan
    Jun 27, 2019
    4
    new 的怎么能调用 spring 容器的 bean ;
    guoyuchuan
    guoyuchuan
    Jun 27, 2019
    5
    new 之前在类中加载 spring 容器就行;
    方法很多,百度 spring Aware 接口 就知道怎么做了;
    gz911122
    gz911122
    Jun 27, 2019
    6
    UdpServerThread 被 spring 管理了吗
    guoyuchuan
    guoyuchuan
    Jun 27, 2019
    7
    alangz
    alangz
    Jun 27, 2019
    8
    你自己实例化的对象自然没法直接让 Spring 帮你注入依赖,你需要获取到 IoC 的上下文(多种方式),然后通过这个上下文来拿到被 Spring 管理的 Bean。
    Spring 的核心还是应该多看看。
    arthas2234
    arthas2234
    Jun 27, 2019
    9
    不要通过 new 来启动,可以使用 @PostConstruct 注解或者实现 ApplicationRunner、CommandLineRunner 接口来启动
    你的 handler 也要设成组件并通过注入来初始化
    nutting
    nutting
    Jun 27, 2019
    10
    用 spring 你就都得 spring 接管对象才能依赖
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2319 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 13:18 · PVG 21:18 · LAX 05:18 · JFK 08:18
    ♥ Do have faith in what you're doing.