I am having a Repository
through which I'm getting data from Elasticsearch. It is working correctly when I send a GEt
request.
I need that data from Elasticsearch without sending a GET
request for which I've written a Service
and annotated that repository in Service
class using @Autowired
.
Repository
@Repository
public interface RecipeDtoRepository extends
ElasticsearchRepository<RecipeDto, Integer> {}
Controller
@RestController
@RequestMapping("/repo")
public class RecipeRepoController {
@Autowired
public RecipeDtoRepository recipeDtoRepository;
@GetMapping("/all")
public String getRecipes() {
List<RecipeDto> recipe_list = new ArrayList<>();
recipeDtoRepository.findAll().forEach(recipe_list::add);
return recipe_list.toString();
}
Service
@Service
@Component
public class ClusterService implements ApplicationContextAware {
@Autowired
public RecipeDtoRepository recipeDtoRepository;
List<RecipeDto> recipe_list = new ArrayList<>();
new ClusterService(). applicationContext.getBean(RecipeRepoController.class).recipeDtoRepository.findAll().forEach(recipe_list::add);
}
@Override
public void setApplicationContext(ApplicationContext
applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
Problem
when calling the method in controller using GET
request, it is working fine but when I call it using Service
class, it is throwing NullPointerException
which it shouldn't be according to my knowledge. I read an article where it was suggested to get the Bean
in Service
class which you can see I've done using ApplicationContext
but it is throwing that exception. I've tried it without using ApplicationContext
and it throws NullPointerException
in that case too. I'm working over it for the last two days and unable to find a solution.
@Service
@Configurable
public class ClusterService {
@Autowired
public RecipeDtoRepository recipeDtoRepository;
private String getRecipes() {
List<RecipeDto> recipe_list = new ArrayList<>();
recipeDtoRepository.findAll().forEach(recipe_list::add);
return recipe_list.toString();
}
public static void main(String[] a) {
ClusterService clusterService = new ClusterService();
clusterService.getRecipes();
}}