Light777
@Light777
Developer

Почему @Autowired возвращает NullPointerException?

Связал JavaFX с Spring Boot. Пытаюсь подвязать SettingsEntityRepository к MyController. Поискал в инете, но у всех эта проблема вызвана оператором NEW . Странно что при подаче в ClassPathResource fxml класса MyController-а , все работает норм
package com.fx.springfx.entity;

@Entity
@Table(name = "Settings")
@Data
@NoArgsConstructor
public class SettingsEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Basic
    @Column(name = "CODE")
    private String code;
    @Basic
    @Column(name = "PORT")
    private String port;
    @Basic
    @Column(name = "INTERFACE")
    private String interfaceType;
    @Basic
    @Column(name = "SIMCARD")
    private String simCard;
    @Basic
    @Column(name = "ISMODEM")
    private boolean isModem;

    public SettingsEntity(String code, String port, String interfaceType) {
        this.code = code;
        this.port = port;
        this.interfaceType = interfaceType;
    }
}


package com.fx.springfx.repository;
@Repository //@Component такая же ошибка
public interface SettingsEntityRepository extends JpaRepository<SettingsEntity, Long> {

    SettingsEntity getByCode(String code);

}

package com.fx.springfx.controller.admin;


@Component
public class MyController {

    @Autowired
    private SettingsEntityRepository settingsEntityRepository;//----- Here Always NULL

    @FXML
    private Button saveBtn;

    @FXML
    void initialize() {

        saveBtn.setOnAction(event -> {

            SettingsEntity p = new SettingsEntity("a", "123", "zxc");
            settingsEntityRepository.save(p);

        });
  }
}


package com.fx.springfx;

public class JavaFXApp extends Application {

    private ConfigurableApplicationContext context;

    @Override
    public void init() {
        ApplicationContextInitializer<GenericApplicationContext> initializer =
                context -> {
                    context.registerBean(Application.class, () -> JavaFXApp.this);
                    context.registerBean(Parameters.class, this::getParameters);
                    context.registerBean(HostServices.class, this::getHostServices);
                };
        this.context = new SpringApplicationBuilder()
                .sources(SpringfxApplication.class)
                .initializers(initializer)
                .run(getParameters().getRaw().toArray(new String[0]));
    }

    @Override
    public void start(Stage stage) throws IOException {
        this.context.publishEvent(new StageReadyEvent(stage));
    }

    @Override
    public void stop() throws Exception {
        this.context.close();
        Platform.exit();
    }
}

@Component
class StageInitializer implements ApplicationListener<StageReadyEvent> {

    private final String applicationTitle;
    private final ApplicationContext applicationContext;

    StageInitializer(@Value("${spring.application.ui.title}") String applicationTitle,
                     ApplicationContext applicationContext) {
        this.applicationTitle = applicationTitle;
        this.applicationContext = applicationContext;
    }

    @Override
    public void onApplicationEvent(StageReadyEvent stageReadyEvent) {
        try {
            Stage stage = stageReadyEvent.getStage();
            ClassPathResource fxml = new ClassPathResource("/fxml/admin/Login.fxml");
            //ClassPathResource fxml = new ClassPathResource("/fxml/admin/MyController.fxml");
            FXMLLoader fxmlLoader = new FXMLLoader(fxml.getURL());
            fxmlLoader.setControllerFactory(this.applicationContext::getBean);
            Parent root = fxmlLoader.load();
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.setTitle(this.applicationTitle);
            //stage.setMaximized(true);
            stage.show();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

class StageReadyEvent extends ApplicationEvent {

    private final Stage stage;

    StageReadyEvent(Stage stage) {
        super(stage);
        this.stage = stage;
    }

    public Stage getStage() {
        return stage;
    }
}


package com.fx.springfx;

@SpringBootApplication
public class SpringfxApplication {

    public static void main(String[] args) {
        //SpringApplication.run(SpringfxApplication.class, args);
        Application.launch(JavaFXApp.class, args);
    }


}
  • Вопрос задан
  • 158 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽
19 апр. 2024, в 23:00
5000 руб./за проект
19 апр. 2024, в 20:43
20000 руб./за проект