我正在使用 spring 框架創建一個 Netty UDP 服務器。我有 3 個類和 1 個接口。UDPServer.javapackage 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(); }}
2 回答

德瑪西亞99
TA貢獻1770條經驗 獲得超3個贊
你的類IncomingPacketHandler
不是由 Spring 管理的,而是由你親自創建的:
ChannelPipeline p = ch.pipeline(); p.addLast(new IncomingPacketHandler());
因此,即使您添加一百萬個 Spring 注釋,它們也不會執行任何操作。您想要的是讓 Spring 創建此處理程序,并將 Spring 創建的處理程序作為參數傳遞給p.addLast

蕭十郎
TA貢獻1815條經驗 獲得超13個贊
該類IncomingPacketHandler是手動創建的,而不是由 Spring 創建的,因此bean不可用。
添加@Component到IncomingPacketHandler類:
...
import org.springframework.stereotype.Component;
@Component
public class IncomingPacketHandler extends
...
然后在UDPServer.java:
...
import org.springframework.beans.factory.annotation.Autowired;
@Component
public class UDPServer {
@Autowired
private IncomingPacketHandler incomingPacketHandler;
...
添加回答
舉報
0/150
提交
取消