Matahari
Matahari

Reputation: 109

Spring boot JPA null pointer exception

I am developing an JavaFx application with spring boot,JPA, and H2. I have a user entity when I try to add a new user into the DB it throws NPE in the controller on the button's click action. As it is seen I use only autowire notation. I researched but findings did not help out. Any help please?

package com.core;

@SpringBootApplication
@Import(SharedSpringConfiguration.class)
public class Runner extends Application {

   private ConfigurableApplicationContext context;

   public static void main(String[] args) {
     launch(args);        
   }

   @Override
   public void init() {
    context = SpringApplication.run(Runner.class);
   }
}
package com.dao;

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

    @Id
    @Column(name = "id", updatable = false, nullable = false)
    private long ID;
    @Column(nullable = false)
    private String userName;
    @Column(nullable = false)
    private String userPass;

    public User() {
    }

    public User(long ID, String userName, String userPass) {
        this.ID = ID;
        this.userName = userName;
        this.userPass = userPass;
    }
}
package com.service;

@Service
public class UserService {

   @Autowired
   private UserRepository userRepository;

   public UserService() {
   }

   public void saveUser(User user) {
     userRepository.save(user);
   }
}
package com.repository;
public interface UserRepository extends CrudRepository<User, Long> {}
package com.controller

@Controller
public class MethodController implements Initializable {

  @Autowired
  private UserService userService;

  @FXML
  void methodSave(MouseEvent event) {
    userService.saveUser(new User(11, "TestUser", "noPass")); //Throws NPE. Indicates that userService is null. But I autowire the userService.
  }
}

Upvotes: 0

Views: 1775

Answers (2)

Kathirvel Subramanian
Kathirvel Subramanian

Reputation: 684

Change your SpringBootApplication package from com.core to com

because SpringBootApplication by default will scan only that packages and sub packages.

else

add @ComponentScan annotation in SpringBootApplication and scan the packages.

Upvotes: 0

Alex Wittig
Alex Wittig

Reputation: 2900

I don't know what's in SharedSpringConfiguration, but you probably need @EnableJpaRepositories on one of your configuration classes. @Repository on the CrudRepo should be unnecessary.

Upvotes: 2

Related Questions