Injecting and Wiring in Spring with annotations

In the previous I have sketched a component structure for a Spring Web application and I mock-tested with Mockito. Now I am going to create a concrete components and to wire them together.

I create a concrete Quest, annotated so that Spring sees it as a Component qualified as quest.
public class SlayDragonQuest implements Quest {
    public String embark() {
        return "Embarking on quest to slay the dragon!";
I annotate the BraveKnight component, that Springs can now manage directly the wiring on its own, using in the Constructor Injection a component qualified as quest.
public class BraveKnight implements Knight {
    // ...
    public BraveKnight(@Qualifier("quest") Quest quest) { = quest;
 // ...
Spring tries to inject in the resource owned by the controller, seen in the previous post, a component with the same name as its Java type (lowercase fist letter, though), and then maps the call the the /quest URI using the controller method annotated as request mapping.

Once the Spring Web app is started in the Boot Dashboard, we can consume the service from a browser.

I have written this post while reading the first chapter of Spring in Action, Fourth Edition by Craig Walls. While doing it, I have ported the original code to a Maven Spring Boot Web project on the STS IDE, using AspectJ annotations instead of using the classic xml configuration.

Full code on github.

No comments:

Post a Comment