Spring Boot Autowired Repository null

我正在使用 spring 框架创建一个 Netty UDP 服务器。我有 3 个类和 1 个接口。


UDPServer.java


package com.example.nettyUDPserver;


import java.net.InetAddress;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import org.springframework.stereotype.Component;


import akka.actor.ActorRef;

import io.netty.bootstrap.Bootstrap;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.ChannelOption;

import io.netty.channel.ChannelPipeline;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.nio.NioDatagramChannel;



public class UDPServer {

    private int port;

    ActorRef serverActor = null;


    public UDPServer(int port) {

        this.port = port;

    }


    public void run() throws Exception {

        final NioEventLoopGroup group = new NioEventLoopGroup();

        try {

            final Bootstrap b = new Bootstrap();

            b.group(group)

                .channel(NioDatagramChannel.class)

                .option(ChannelOption.SO_BROADCAST, true)

                .handler(new ChannelInitializer<NioDatagramChannel>() {

                    @Override

                    public void initChannel(final NioDatagramChannel ch) throws Exception {

                        ChannelPipeline p = ch.pipeline();

                        p.addLast(new IncomingPacketHandler());

                    }

                });


            Integer pPort = port;

            InetAddress address = InetAddress.getLocalHost();

            //InetAddress address = InetAddress.getByName("192.168.1.53");

            System.out.println("Localhost address is: " + address.toString());

            b.bind(address, pPort).sync().channel().closeFuture().await();

        } finally {

            group.shutdownGracefully().sync();

        }

    }


    public static void main(String[] args) throws Exception {

        int port = 6001;

        new UDPServer(port).run();

    }

}


POPMUISE
浏览 254回答 2
2回答

德玛西亚99

你的类IncomingPacketHandler不是由 Spring 管理的,而是由你亲自创建的:ChannelPipeline&nbsp;p&nbsp;=&nbsp;ch.pipeline(); p.addLast(new&nbsp;IncomingPacketHandler());因此,即使您添加一百万个 Spring 注释,它们也不会执行任何操作。您想要的是让 Spring 创建此处理程序,并将 Spring 创建的处理程序作为参数传递给p.addLast

萧十郎

该类IncomingPacketHandler是手动创建的,而不是由 Spring 创建的,因此bean不可用。添加@Component到IncomingPacketHandler类:...import org.springframework.stereotype.Component;@Componentpublic class IncomingPacketHandler extends...然后在UDPServer.java:...import org.springframework.beans.factory.annotation.Autowired;@Componentpublic class UDPServer {@Autowiredprivate IncomingPacketHandler incomingPacketHandler;...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java