0

So I had no problems with my app until I decided that it's better to have a Service class to do all the logic stuff. And when i copy the exact same code that i initially had, i get NullPointer error.

This is what i had and it worked all well:

User user = userRepository.findById(id).get();

This is what i have in Service class:

public User findUserById(Integer id)
    {
        User user = userRepository.findById(id).get();
        return user;
    }

And this is what i call:

private UserService userService = new UserService();
User user = userService.findUserById(id);

1 Answers1

1

If you're calling new UserService() it's not a Spring bean and won't get autowired.

There are multiple ways to create a Spring bean:

  1. Annotate your class with @Service and making sure it's part of the component scan for your app. Also make sure the repository field is annotated with @Autowired or that your service class has a constructor that accepts the repository as an argument.
    @Service
    public class UserService {

        @Autowired
        private UserRepository userRepository;
    } 
  1. Create a class annotated with @Configuration and then add a @Bean method that returns a new instance of your service:
    @Configuration
    public class UserServiceConfig {

        @Bean
        public UserService userService(UserRepository userRepository) {
            return new UserService(userRepository); // could also use a setter instead
        }
    }
Mike
  • 4,722
  • 1
  • 27
  • 40