我有这些课。当我调试时,我看到spring在构造函数中创建了服务对象,并在两个类中都调用了构造函数,但是当我想使用这些字段时,它们为null。有什么问题?! (type1Processor,type2Processor和type3Processor为空)

import com.vali.ReactiveSocketServer.service.ReceivedDataService;
import org.springframework.stereotype.Component;

public abstract class Processor {

public ReceivedDataService receivedDataService;

public Processor(ReceivedDataService receivedDataService) {
    this.receivedDataService = receivedDataService;
}

public abstract void readStream(String stream);
}


这是它的子类

import com.vali.ReactiveSocketServer.model.ReceivedData;
import com.vali.ReactiveSocketServer.service.ReceivedDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Type1Processor extends Processor {


@Autowired
public Type1Processor(ReceivedDataService receivedDataService) {
    super(receivedDataService);
}

@Override
public void readStream(String stream) {
    System.out.println("readStream "+ getClass().getSimpleName() + "-" + stream);
    receivedDataService.add(new ReceivedData(stream.getBytes()));
}
}


这是它的用法:

import com.vali.ReactiveSocketServer.processor.Processor;
import com.vali.ReactiveSocketServer.processor.Type1Processor;
import com.vali.ReactiveSocketServer.processor.Type2Processor;
import com.vali.ReactiveSocketServer.processor.Type3Processor;
import com.vali.ReactiveSocketServer.receivers.AppServer;
import com.vali.ReactiveSocketServer.socket.ClientHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
public class ReactiveSocketServerApplication {

private AppServer appServer;

@Autowired
Type1Processor type1Processor;

@Autowired
Type2Processor type2Processor;

@Autowired
Type3Processor type3Processor;

public static void main(String[] args) {
    SpringApplication.run(ReactiveSocketServerApplication.class, args);

    ReactiveSocketServerApplication reactiveSocketServerApplication = new ReactiveSocketServerApplication();
    reactiveSocketServerApplication.Start();
}


public void Start(){

    appServer = AppServer.getInstance();

    Map<Integer, Processor> processorMap = new HashMap<>();

    processorMap.put(7001, type1Processor);
    processorMap.put(7002, type2Processor);
    processorMap.put(7003, type3Processor);

    appServer.initialize(processorMap);

    new ClientHandler(7001, 1000);
    new ClientHandler(7002, 5000);
}
}

最佳答案

您正在自己实例化ReactiveSocketServerApplication

因为实例是在生命周期之外创建的,所以spring不能注入@Autowired带注释的bean。

完全删除此内容:

ReactiveSocketServerApplication reactiveSocketServerApplication = new ReactiveSocketServerApplication();
reactiveSocketServerApplication.Start();


并用Start()注释您的@PostConstruct

@PostConstruct
public void Start() { ... }

10-08 15:58