Caused by: java.lang.NullPointerException: "this.masterDao" is null
Я начинающий программист, делаю свой проект на javaFX и Spring, при попытке зарегистрироваться, у меня возникает ошибка с MasterDao (слоя для взаимодействия с базой данных), пишет что он пустой, хотя при авторизации все работает корректно, ниже прилагаю LoginController, RegistrationController (который работает), main и Spring конфиг а так же ссылку на свой проект в git-hub, очень надеюсь на вашу помощь)
package project.orgtech.frontController.auth;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import project.orgtech.StartApplication;
import project.orgtech.dao.MasterDao;
import project.orgtech.models.Master;
import java.io.IOException;
@Controller
public class LoginController {
@Autowired
private MasterDao masterDao; // Injected by Spring
@FXML
private TextField loginText;
@FXML
private PasswordField passwordText;
@FXML
private Button loginButton;
@FXML
private Button registrationButton;
@FXML
private void handleLoginButton(ActionEvent event) throws IOException {
Master master = masterDao.findMasterByLogin(loginText.getText());
if (master != null && master.getPassword().equals(passwordText.getText())) {
Stage currentStage = (Stage) loginButton.getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/project/orgtech/request/main-view.fxml"));
loader.setControllerFactory(StartApplication.getContext()::getBean);
Parent root = loader.load();
Stage newStage = new Stage();
newStage.setTitle("Главное окно");
newStage.setScene(new Scene(root));
newStage.show();
currentStage.close();
} else {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Ошибка");
alert.setHeaderText(null);
alert.setContentText("Логин или пароль неверный");
alert.showAndWait();
}
}
@FXML
private void handleRegistrationButton(ActionEvent event) throws IOException {
Stage currentStage = (Stage) registrationButton.getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/project/orgtech/auth/registration-view.fxml"));
Parent root = loader.load();
Stage newStage = new Stage();
newStage.setTitle("Регистрация");
newStage.setScene(new Scene(root));
newStage.show();
currentStage.close();
}
@FXML
void initialize() {
// Initialization logic if necessary
}
}
package project.orgtech.frontController.auth;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import project.orgtech.dao.MasterDao;
import project.orgtech.models.Master;
import java.io.IOException;
@Controller
public class RegistrationController {
@Autowired
private MasterDao masterDao; // Injected by Spring
@FXML
private TextField loginText;
@FXML
private PasswordField passwordText;
@FXML
private TextField firstNameText;
@FXML
private TextField lastNameText;
@FXML
private TextField middleNameText;
@FXML
private Button registerButton;
@FXML
private Button backButton;
@FXML
private void handleRegisterButton(ActionEvent event) throws IOException {
String login = loginText.getText();
String password = passwordText.getText();
String firstName = firstNameText.getText();
String lastName = lastNameText.getText();
String middleName = middleNameText.getText();
if (login.isEmpty() || password.isEmpty() || firstName.isEmpty() || lastName.isEmpty()) {
showAlert("Ошибка", "Все поля должны быть заполнены");
return;
}
Master newMaster = new Master();
newMaster.setLogin(login);
newMaster.setPassword(password);
newMaster.setFirstName(firstName);
newMaster.setLastName(lastName);
newMaster.setMiddleName(middleName);
masterDao.addMaster(newMaster);
showAlert("Успех", "Регистрация прошла успешно");
navigateToLogin();
}
@FXML
private void handleBackButton(ActionEvent event) throws IOException {
navigateToLogin();
}
private void navigateToLogin() throws IOException {
Stage currentStage = (Stage) backButton.getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/project/orgtech/auth/login-view.fxml"));
Parent root = loader.load();
Stage newStage = new Stage();
newStage.setTitle("Вход");
newStage.setScene(new Scene(root));
newStage.show();
currentStage.close();
}
private void showAlert(String title, String content) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(content);
alert.showAndWait();
}
@FXML
void initialize() {
// Initialization logic if necessary
}
}
package project.orgtech.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@ComponentScan(basePackages = "project.orgtech")
public class dbConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/postgres");
dataSource.setUsername("postgres");
dataSource.setPassword("pass");
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("project.orgtech");
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
return properties;
}
}
package project.orgtech;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import lombok.Getter;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import project.orgtech.config.dbConfig;
public class StartApplication extends Application {
@Getter
private static AnnotationConfigApplicationContext context;
public static void main(String[] args) {
// Initialize Spring context
context = new AnnotationConfigApplicationContext(dbConfig.class);
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/project/orgtech/auth/login-view.fxml"));
loader.setControllerFactory(context::getBean); // Use Spring context to load controllers
Parent root = loader.load();
primaryStage.setTitle("Вход");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
@Override
public void stop() throws Exception {
super.stop();
context.close(); // Close Spring context when application stops
}
}
https://github.com/AleksandrSherbakov/Org-Tech/tree/main/src/main
Ответы (1 шт):
Я нашел в чем было дело, спринг не мог создать бин так как у меня не был прописан конфиг при вызове для страницы RegistrationController, в классе Main он был
loader.setControllerFactory(StartApplication.getContext()::getBean);
добавил эту строку и все заработало :)