简体   繁体   English

从接口扩展的单例类的依赖注入

[英]Dependency Injection of Singleton Class that extends from Interface

I have a Singleton class ReadingStratgeyImp that extends from an Interface ReadingStrategy .我有一个Singleton类ReadingStratgeyImp从一个接口扩展ReadingStrategy In readingStrategyImp-getInstance() method will return the instance of ReadingStrategyImp .readingStrategyImp-getInstance()方法返回的实例ReadingStrategyImp

Here is my query: I want to inject the dependency of ReadingStrategyImp in a few of the other classes of the project.这是我的查询:我想在项目的其他几个类中注入ReadingStrategyImp的依赖项。 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:如果我理解你的问题是正确的,你应该先用 ReadingStrategyImp 为 ReadingStrategy 创建一个 Bean:

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

Then you could just autowire the ReadingStrategy where you need it.然后,您可以在需要的地方自动装配 ReadingStrategy。

@Autowired ReadingStrategy readingStrategy;

Its always better to depend on interfaces not on concrete classes.依赖接口而不是具体类总是更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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