依赖注入继承自接口的单例类

huangapple go评论55阅读模式
英文:

Dependency Injection of Singleton Class that extends from Interface

问题

我有一个名为ReadingStrategyImp的单例类,它继承自一个接口ReadingStrategy。在readingStrategyImp-getInstance()方法中,将返回ReadingStrategyImp类的实例。

以下是您的查询:
我想要在项目的几个其他类中注入ReadingStrategyImp的依赖关系。
我通过以下代码实现了这一点:

    ReadingStrategy readingStrategy;

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

我想知道如何注入这个依赖关系。

英文:

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.

答案1

得分: 1

@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.
英文:

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.

答案2

得分: 0

如果我理解你的问题正确,你应该首先为ReadingStrategy创建一个名为ReadingStrategyImp的Bean:

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

然后在需要的地方,你可以直接自动装配ReadingStrategy。

@Autowired
ReadingStrategy readingStrategy;

依赖于接口而不是具体类通常是更好的做法。

英文:

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.

huangapple
  • 本文由 发表于 2020年10月2日 23:06:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64173904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定