简体   繁体   中英

Dependency Injection of Singleton Class that extends from Interface

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM