V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
zy2019
V2EX  ›  Java

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

  •  
  •   zy2019 · 2019-06-27 16:19:42 +08:00 · 2999 次点击
    这是一个创建于 1758 天前的主题,其中的信息可能已经有所发展或是发生改变。

    项目 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 条回复    2019-06-27 18:27:48 +08:00
    hfc
        1
    hfc  
       2019-06-27 17:03:19 +08:00
    UdpServerThread 类中加一个成员变量,再通过 set 方法赋值
    anakinsky
        2
    anakinsky  
       2019-06-27 17:03:25 +08:00
    封装个 SpringBeanUtils,beanFactory.getBean(beanName);
    Ahaochan
        3
    Ahaochan  
       2019-06-27 17:10:00 +08:00
    guoyuchuan
        4
    guoyuchuan  
       2019-06-27 17:35:58 +08:00
    new 的怎么能调用 spring 容器的 bean ;
    guoyuchuan
        5
    guoyuchuan  
       2019-06-27 17:39:18 +08:00
    new 之前在类中加载 spring 容器就行;
    方法很多,百度 spring Aware 接口 就知道怎么做了;
    gz911122
        6
    gz911122  
       2019-06-27 17:39:20 +08:00
    UdpServerThread 被 spring 管理了吗
    guoyuchuan
        7
    guoyuchuan  
       2019-06-27 17:41:20 +08:00
    alangz
        8
    alangz  
       2019-06-27 17:43:42 +08:00
    你自己实例化的对象自然没法直接让 Spring 帮你注入依赖,你需要获取到 IoC 的上下文(多种方式),然后通过这个上下文来拿到被 Spring 管理的 Bean。
    Spring 的核心还是应该多看看。
    arthas2234
        9
    arthas2234  
       2019-06-27 18:19:49 +08:00
    不要通过 new 来启动,可以使用 @PostConstruct 注解或者实现 ApplicationRunner、CommandLineRunner 接口来启动
    你的 handler 也要设成组件并通过注入来初始化
    nutting
        10
    nutting  
       2019-06-27 18:27:48 +08:00
    用 spring 你就都得 spring 接管对象才能依赖
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2964 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 03:33 · PVG 11:33 · LAX 20:33 · JFK 23:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.