简体   繁体   中英

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.
  }
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM