0

I am learning Spring boot with Javafx. I am trying to make a simple application with Embedded H2 database. I have created a simple entity.

@Entity
@Table(name="User")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column
    private long id;
    @Column
    private String firstName;
    @Column
    private String lastName;
    @Column
    private String email;
    @Column
    private String password;

   // With getters and setter
}

And a repository

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

And a service

@Service
public class UserService {

    @Autowired
    UserRepository userRepository;

    public List<User> findAll(){
        return userRepository.findAll();
    }
}

And my entry point for the app is:

import com.waq.repository.UserRepository;
import com.waq.service.UserService;
import javafx.application.Application;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class MmsApplication extends Application{

    @Autowired
    UserService userService;

    protected ConfigurableApplicationContext springContext;

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

    @Override
    public void init() throws Exception {
        springContext = springBootApplicationContext();
    }

    private ConfigurableApplicationContext springBootApplicationContext() {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(MmsApplication.class);
        String[] args = getParameters().getRaw().stream().toArray(String[]::new);
        return builder.run(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.show();
        //System.out.println("Users: " + userService.findAll());  // Throws exception
        System.out.println(springContext.getBean(UserService.class).findAll()); // It works
    }
}

Stacktrace:

    2019-02-17 17:08:28.547  INFO 12128 --- [JavaFX-Launcher] o.s.boot.SpringApplication               : Starting application on waq-PC with PID 12128 (started by waq in E:\springiodemo)
2019-02-17 17:08:28.554  INFO 12128 --- [JavaFX-Launcher] o.s.boot.SpringApplication               : No active profile set, falling back to default profiles: default
2019-02-17 17:08:29.945  INFO 12128 --- [JavaFX-Launcher] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-02-17 17:08:30.044  INFO 12128 --- [JavaFX-Launcher] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 89ms. Found 1 repository interfaces.
2019-02-17 17:08:30.892  INFO 12128 --- [JavaFX-Launcher] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-02-17 17:08:31.233  INFO 12128 --- [JavaFX-Launcher] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-02-17 17:08:31.348  INFO 12128 --- [JavaFX-Launcher] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-02-17 17:08:31.523  INFO 12128 --- [JavaFX-Launcher] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.7.Final}
2019-02-17 17:08:31.527  INFO 12128 --- [JavaFX-Launcher] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-02-17 17:08:31.808  INFO 12128 --- [JavaFX-Launcher] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-02-17 17:08:32.442  INFO 12128 --- [JavaFX-Launcher] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2019-02-17 17:08:33.738  INFO 12128 --- [JavaFX-Launcher] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-02-17 17:08:34.675  INFO 12128 --- [JavaFX-Launcher] o.s.boot.SpringApplication               : Started application in 7.195 seconds (JVM running for 8.368)
Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at com.waq.MmsApplication.start(MmsApplication.java:40)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    ... 1 more
2019-02-17 17:08:34.977  INFO 12128 --- [       Thread-6] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-02-17 17:08:34.991  INFO 12128 --- [       Thread-6] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2019-02-17 17:08:35.026  INFO 12128 --- [       Thread-6] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

I can"t figure out why it is throwing null pointer exception using @Autowired but if I use getBean then it works. It would be great if someone can explain where is the problem. Thanks.

Edit:

I tried with CommandLineRunner and it works:

package com.waq;
import com.waq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application implements CommandLineRunner {
    @Autowired
    UserService userService;
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Override
    public void run(String... arg0) throws Exception {
        System.out.println(userService.findAll());
    }
}

Still can"t figure out why it is not working in the above main.

Waqar Ahmed
  • 5,005
  • 2
  • 23
  • 45
  • Presse post Thema stack trace here. – keuleJ Feb 17 '19 at 15:01
  • Please use **@Autowired** with **protected ConfigurableApplicationContext springContext**. – kamlesh pandey Feb 17 '19 at 15:10
  • @kamleshpandey Thanks for that. but I would like to know about the other exception. – Waqar Ahmed Feb 17 '19 at 15:11
  • I tried to run the same code on my system it threw exception for **springContext.getBean(UserService.class).findAll()**. can you please check logs once again – kamlesh pandey Feb 17 '19 at 15:13
  • @kamleshpandey If I initialized the springContext in a way which I wrote above, it works. But if I use Autowired with springContext, it throws null pointer exception. – Waqar Ahmed Feb 17 '19 at 15:22
  • @fabian I renamed it and for simplicity i removed the imports and other parts. And spring context is in init method. – Waqar Ahmed Feb 17 '19 at 16:07
  • @fabian I have posted the all code with imports and correct name. – Waqar Ahmed Feb 17 '19 at 16:09
  • Note that JavaFX, not spring creates the instance of `MmsApplication`. Spring does no injection in this case. How to inject to an existing object is described here: https://stackoverflow.com/questions/3813588/how-to-inject-dependencies-into-a-self-instantiated-object-in-spring ; not sure, if you need to change something spring-boot related... – fabian Feb 17 '19 at 16:48
  • @fabian what would be the correct way to initialize the javafx application with spring DI (@Autowired) ? – Waqar Ahmed Feb 17 '19 at 16:53
  • the nullpointer is in `getParameters()` or `getRaw()`.. – xerx593 Feb 17 '19 at 18:24
  • @xerx593 Any solution to fix that? – Waqar Ahmed Feb 17 '19 at 18:37
  • ..provide parameters !? :) https://stackoverflow.com/q/31572862/592355 – xerx593 Feb 17 '19 at 18:42
  • ..and if you don't have parameters, then you might not need `args` ...pass `null`an `{}` or use `return builder.run();` – xerx593 Feb 17 '19 at 18:45
  • @xerx593 no, Its not a problem of parameters. It's a problem with autowiring. – Waqar Ahmed Feb 17 '19 at 18:46

0 Answers0