英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论