[英]Is passing a service as a parameter bad practice?
Suppose I want to use a service in a POJO class, like an implementation of some sort, can I just pass this service as a parameter to this POJO?假设我想在 POJO class 中使用服务,就像某种实现一样,我可以将此服务作为参数传递给此 POJO 吗? Or would that be bad practice?
或者那是不好的做法?
@Service
public class MyService {
// Inject AnotherService in this service
public MyService(AnotherService anotherService) {
// Now pass that service in a POJO
SomeImplementation impl = new SomeImplementation(anotherService);
}
}
public class SomeImplementation {
public SomeImplementation(AnotherService anotherService) {
// start using the AnotherService here...
}
}
For this example I used Java and Spring, but this question applies to all languages with dependency injection.对于这个例子,我使用了 Java 和 Spring,但这个问题适用于所有具有依赖注入的语言。
I would say that it's just not making use of the framework you're operating within.我会说它只是没有利用您正在运行的框架。 That's exactly what DI is for: letting the container handle the components and their relations (eg. if you inject sth multiple times, DI helps you avoid multiple instantiations).
这正是 DI 的用途:让容器处理组件及其关系(例如,如果您多次注入,DI 可以帮助您避免多次实例化)。
Now, in your case, you can use the @Configurable
annotation, which adds a POJO component to the Spring context, and so lets you inject stuff into it.现在,在您的情况下,您可以使用
@Configurable
注释,它将 POJO 组件添加到 Spring 上下文中,因此您可以将内容注入其中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.