Search code examples
javaspringspring-bootdependency-injectionspring-annotations

Spring Dependency Injection missing bean


I am trying to implement Constructor based Dependency Injection with Spring. From Spring 4.3 annotations are not required for constructor injection, so my class looks like this:

@RestController
public class CardController {

    private IDeckManager _deckManager;

    public CardController(IDeckManager deckManager){
        _deckManager = deckManager;
    }

    @RequestMapping("/preparedeck")
    public void PrepareDeck(){
        _deckManager.InitializeDeck();
        _deckManager.ShuffleDeck();
    }
}

where IDeckManager is:

public interface IDeckManager {

    void InitializeDeck();

    void ShuffleDeck();
}

and the actual implementation of IDeckManager is:

public class DeckManager implements IDeckManager {

    public Stack<Card> deck;

    public DeckManager() {
        deck = new Stack<Card>();
    }

    @Override
    public void InitializeDeck() {

        for (int i = 0; i < ICard.Suit.length; i++) {
            for (int j = 0; i < ICard.Values.length; i++) {
                deck.add(new Card(ICard.Suit[i], ICard.Values[j]));
            }
        }
    }

    @Override
    public void ShuffleDeck() {
        Collections.shuffle(deck);
    }
}

Unfortunately at runtime it says that: Parameter 0 of constructor in CardController required a bean of type IDeckManager that could not be found.

What am I missing to make the DI work properly?


Solution

  • Spring need to identify DeckManager as Spring managed bean, if you use component scan add @Service or @Component annotation on implementation

    @Service
    public class DeckManager implements IDeckManager {
    

    Or add it in Configuration class as a Bean

    @Bean
    IDeckManager deckManager() {
       return new DeckManager();
    }