Dependency Injection of Singleton Class that extends from Interface

Viewed 284

I have a Singleton class ReadingStratgeyImp that extends from an Interface ReadingStrategy. In readingStrategyImp-getInstance() method will return the instance of ReadingStrategyImp.

Here is my query: I want to inject the dependency of ReadingStrategyImp in a few of the other classes of the project. I am achieving this by below code

    ReadingStrategy readingStrategy;

    @Autowired
    public void setReadingStrategy(ReadingStrategyImp readingStrategy) {
        this.readingStrategy = ReadingStrategyImp.getInstance();
    }

I want to know how one will inject the dependency.

2 Answers

You simply do this :

@Component
public class Sample {

  // spring will automatically find the implementation class and inject it. 
  // so, the ReadingStrategyImp class will automatically injected. 
  @Autowired 
  @Qualifier("readingStrategyImp")
  private ReadingStrategy readingStrategy;

}

That's all.

If I understand your question correct, you should create first a Bean for ReadingStrategy with ReadingStrategyImp:

@Bean
public ReadingStrategy readingStrategy() {
   return ReadingStrategyImp.getInstance();
}

Then you could just autowire the ReadingStrategy where you need it.

@Autowired ReadingStrategy readingStrategy;

Its always better to depend on interfaces not on concrete classes.

Related