我正在使用 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条经验 获得超12个赞
该类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
提交
取消