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.
}
}
UserServiceclass you try and autowireUserRepository.UserRepositoryis not setup to be a spring component. Try adding@Repositoryto yourUserRepositoryclass.@Repositorytag did you try? You won't be able to autowireUserRepositorywithout it being scanned by spring.CrudRepository