Spring Boot自动连线资料库null

时间:2019-08-01 09:04:55

标签: java spring spring-boot netty

我正在使用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();
    }
}

IncomingPacketHandler.java

package com.example.nettyUDPserver;

import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import com.example.dao.SensorRepository;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

@ComponentScan("com.example.dao")
public class IncomingPacketHandler extends SimpleChannelInboundHandler<DatagramPacket>  {

    @Autowired
    SensorRepository repo;

    IncomingPacketHandler(){

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        final InetAddress srcAddr = packet.sender().getAddress();

        ByteBuf buffer = packet.content();
        packet.replace(buffer);
        int len = buffer.readableBytes();
        byte[] message = new byte[len];
        buffer.readBytes(message);
        String str = new String(message, StandardCharsets.UTF_8);

        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(str);

        int id = actualObj.get("sensor_id").asInt();
        String status = actualObj.get("status").asText();

        System.out.println("==========================================================");
        System.out.println("Source address of datagram received: " + srcAddr.toString());
        System.out.println("String message received: " + str);
        show();
    }

    public void show() {
        System.out.println("In show function, we will perform our CRUD operations");
        System.out.println(repo);
//      try {
//          this.repo.findAll().forEach(x -> System.out.println(x));
//      } catch (NullPointerException e) {
//          e.printStackTrace();
//      }

    }

}

Sensor.java

package com.example.models;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Sensor {

    @Id
    private int sensor_id;
    private String status;
    private double batLev;

    public int getSensor_id() {
        return sensor_id;
    }

    public void setSensor_id(int sensor_id) {
        this.sensor_id = sensor_id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public double getBatLev() {
        return batLev;
    }

    public void setBatLev(double batLev) {
        this.batLev = batLev;
    }


}

SensorRepository.java

package com.example.dao;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.example.models.Sensor;

@Repository
public interface SensorRepository extends CrudRepository<Sensor, Integer> {

}

我正在类UDPServer.java中运行服务器,并且可以成功获取和解码数据报。问题出在SensorRepository类中的IncomingPacketHandler.java上。我在变量中使用@Autowired表示法,并且在界面中使用@Repository标注,但是当我打印自动装配库的值时,它为null,因此无法进行SQL查询。有什么想法吗?

更新

非常感谢您的回答。我将IncomingPacketHandler类表示为组件,并在UDPServer类中自动装配。当我运行它时,我得到这个:

[nioEventLoopGroup-2-1] DEBUG io.netty.channel.DefaultChannelPipeline - Discarded inbound message DatagramPacket(/192.168.61.64:59905 => /192.168.61.64:6001, PooledUnsafeDirectByteBuf(ridx: 0, widx: 38, cap: 2048)) that reached at the tail of the pipeline. Please check your pipeline configuration.

这可能不在此问题的范围内,但是您可以向我显示方向。再次谢谢你。

2 个答案:

答案 0 :(得分:7)

您的课程IncomingPacketHandler不是由Spring管理的,而是由您亲自创建的:

ChannelPipeline p = ch.pipeline();
p.addLast(new IncomingPacketHandler());

这样,即使您添加一百万个Spring注释,它们也不会做任何事情。相反,您要让Spring创建此处理程序,并将Spring创建的处理程序作为参数传递给p.addLast

答案 1 :(得分:1)

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;
...