1

I am calling a helper class inside a Service Impl. This class should use a bunch of Repositories, which are both Elasticsearch and JPA, and return an object back to the Service Impl. When I inject the repositories via the constructor in that class, I do not get a null for the repository objects.

However, I do not want to have all the repository objects in the constructor as then I would have to use them all as parameters in the Service Impl class using the @Autowired injections on the Service Impl.

For that reason, I tried injection through setters in the UserConverter class but still got nulls.

I configured all the SQL and Elasticsearch related repositories and already got results when injecting the repositories via the constructor.

I am missing something but could not figure out what it is. Hopefully, someone can answer that :) Thanks!

Controller

@Controller
public class MyController {
 private final MyService myService;
 
  @GetMapping("/getUser")
    public ResponseEntity<GlobalSearch> doSearch(@RequestBody RequestData requestData) {
        try {
            User user = myService.getUser(requestData);
            return new ResponseEntity<>(globalSearch, HttpStatus.OK);
        } catch (NoSuchElementException | JsonProcessingException e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

}

Service

public interface MyService{

   User getUser(RequestData requestData);

}

Service Impl

@Service
public class MyServiceImpl implements MyService {
    @Override
    public User getUser(RequestData requestData) {
       User user = new UserConverter().convertUser(requestData);
    }

}

Repository

@Repository
public interface UserRepository extends ElasticsearchRepository<User, String>, UserRepositoryCustom {
}

UserConverter

@Component
public class UserConverter{
  
  private UserRepository userRepository;
  //and at least 5 more JPA or Elasticsearch Repositories after..
  //injection via constructor works tho.

  @Autowired
  public void setUserRepository(UserRepository userRepo) {
     this.userRepository = userRepo;
  }

  public User convertUser(RequestData requestData(){
     int age = userRepository.getAge("joe");
  }

}
Cugomastik
  • 911
  • 13
  • 22
  • 1
    No need to write setter method for userRepository setUserRepository(UserRepository userRepo) and remove this new UserConverter() in MyServiceImpl and autowire UserConverter here also – yahitesh May 05 '22 at 15:34
  • 1
    @Autowire private MyService myService; in controller also – yahitesh May 05 '22 at 15:42
  • Can't thank you enough. You saved the day :) I knew there was a simple solution but could not figure it out. – Cugomastik May 05 '22 at 15:43

0 Answers0