D
D
ddddd tttt2017-03-18 11:18:22
Java
ddddd tttt, 2017-03-18 11:18:22

Why does @Autowired return null?

@Service("manager")
public class Manager_Main {
@Autowired
private Manager_Clients manager_clients;
@Autowired
private Manager_Tur manager_tur;
@Autowired
private Manager_Vaucher manager_vaucher;
Scene scene;

private Manager_Main()
    {
        TabPane tabPane = new TabPane();
        scene = new Scene(tabPane);
        Tab tabC = new Tab("Клиенты");
        tabC.setContent(manager_clients.getGridPane1());
        Tab tabV = new Tab("Путевки");
        tabV.setContent(manager_tur.getGridPane1());
        Tab tabT = new Tab("Туры");
        tabT.setContent(manager_vaucher.getGridPane1());
        tabPane.getTabs().addAll(tabC,tabT,tabV);
    }

    public Scene getScene() {
        return scene;
    }
}

public class Main extends Application {
    private Stage stage;
    public void start(Stage primaryStage) throws Exception {
        setStage(primaryStage);
        primaryStage.setResizable(false);
        GenericXmlApplicationContext gtx = new GenericXmlApplicationContext();
        gtx.load("config.xml");
        gtx.refresh();
        Manager_Main authentication = (Manager_Main) gtx.getBean("manager");
    primaryStage.setScene(authentication.getScene());
    primaryStage.show();
    }

    public Stage getStage() {
        return stage;
    }
    public void setStage(Stage stage) {
        this.stage = stage;
    }
}

All dependencies with the @Component annotation. If Manager_Main() is done as a method with @PostConstruct, and not just a constructor, then everything works. And if Manager_Main() as a constructor, then the dependencies are null. Why so, how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2017-03-18
@zolt85

The guys at Spring don't advise using field autowiring, instead they advise passing your dependencies to the constructor. Those. can be done like this:

private final Manager_Clients manager_clients;
private final Manager_Tur manager_tur;
private Manager_Vaucher manager_vaucher;

@Autowired
public Manager_Main(Manager_Clients manager_clients, Manager_Tur manager_tur, Manager_Vaucher manager_vaucher) {
this.manager_clients = manager_clients;
this.manager_tur = manager_tur;
this.manager_vaucher = manager_vaucher;
}

And yes, most likely your problem is the lack of a default public constructor, empty for example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question