I try to create a simple controller with spring hateoas.
The controller is the following :
@RestController
public class SearchController {
private final List<Plugin> plugins;
@Autowired
public SearchController(List<Plugin> plugins) {
this.plugins = plugins;
}
@GetMapping("/search")
public CollectionModel<PluginDTO> search(
@RequestParam(value = "name", defaultValue = "") String name) {
List<PluginDTO> pluginsDTO = this.plugins.stream()
.filter(plugin -> {
if(name.isBlank()) { // No filter case.
return true;
}
return plugin.getName().toLowerCase(Locale.ROOT).contains(name.toLowerCase(Locale.ROOT));
})
.map(plugin -> new PluginDTO(plugin.getName(), plugin.getDescription(),
plugin.getCapacities().stream().map(c -> new CapacityDTO(c.getName(), c.getDescription())).toList())
.add(
linkTo(methodOn(SearchController.class).one(plugin.getName())).withSelfRel(),
linkTo(methodOn(SearchController.class).search(name)).withRel("search"))
)
.toList();
Link link = linkTo(methodOn(SearchController.class).search(name)).withSelfRel();
return CollectionModel.of(pluginsDTO, link);
}
@GetMapping("/plugin")
private PluginDTO one(@RequestParam(value = "name") String name) {
return this.plugins.stream().filter(plugin -> plugin.getName().equals(name)).findFirst()
.map(plugin -> new PluginDTO(plugin.getName(), plugin.getDescription(),
plugin.getCapacities().stream().map(c -> new CapacityDTO(c.getName(), c.getDescription())).toList())
.add(
linkTo(methodOn(SearchController.class).one("")).withSelfRel(),
linkTo(methodOn(SearchController.class).search("")).withRel("search"))
)
.orElseThrow(() -> new PluginNotFoundException(name));
}
}
With this code linkTo(methodOn(SearchController.class).get(plugin.getName())).withSelfRel()
Spring call the method on()
and throw a NPE
on this.plugin
. It seems that @Autowire
is not resolve in this case.
In the official doc : https://spring.io/guides/tutorials/rest/ Injection seems to work
Any idea why this happen ?
Ok, i missed the private
qualifier use for the method one
. Making the method public solved the problem.