简体   繁体   English

如何选择获取依赖关系的方法?

[英]How to choose between methods of acquiring dependencies?

I've seen at least three ways of acquiring dependencies in a Java object without coupling the object to the creation of the dependency; 我已经看到了至少三种在Java对象中获取依赖关系的方法,而没有将对象耦合到依赖项的创建;

Dependency Injection - some framework injects a required object into another object based on an external configuration, example: Spring managed beans 依赖注入 - 一些框架基于外部配置将所需对象注入另一个对象,例如:Spring托管bean

Dependency Lookup - a class looks up a required dependency in some kind of directory service, example: JNDI lookups in a Java EE container 依赖查找 - 类在某种目录服务中查找必需的依赖项,例如:Java EE容器中的JNDI查找

Static Factories - an object in a global scope provides instances on demand - the standard Java SE APIs seem to be littered with these, example: java.util.Logger.getLogger(name) , java.util.Calendar.getInstance() 静态工厂 - 全局范围内的对象按需提供实例 - 标准Java SE API似乎充满了这些,例如: java.util.Logger.getLogger(name)java.util.Calendar.getInstance()

What guidance can you provide as to which is most appropriate for a situation? 您可以提供哪种指导最适合某种情况?

I prefer dependency injection, because the object need not know how it acquires the references it needs. 我更喜欢依赖注入,因为对象不需要知道它如何获取它所需的引用。

Dependency lookup still requires the object to know about the lookup service and its URL. 依赖关系查找仍然需要对象了解查找服务及其URL。

Static factories are similar to lookup services. 静态工厂与查找服务类似。

I prefer dependency injection . 我更喜欢依赖注入

When I talk about DI with Spring Framework I see following 当我用Spring Framework谈论DI时,我看到了以下内容

  1. It's supported by IDEs (error check, visualization). 它受IDE支持(错误检查,可视化)。
  2. You can setup other needed stuff like AOP, properties loading, ... 你可以设置其他所需的东西,如AOP,属性加载,......
  3. You have big config possibilities - XML, annotation, JavaConfig 您有大的配置可能性 - XML,注释,JavaConfig
  4. Can be use also in desktop application. 也可以在桌面应用程序中使用。

These outbalance every negatives like dependency on another library. 这些因为对依赖另一个库的负面影响而失衡。 Why should I use another approach? 我为什么要使用其他方法?

This really depends on the context. 这实际上取决于上下文。 If you are writing a self-contained Maths API you might want to use static factories because the code will be less verbose, setup-free and maybe more efficient. 如果您正在编写自包含的Maths API,则可能需要使用静态工厂,因为代码将不那么冗长,无需设置且可能更高效。 If you need to access/provide a remote dependency, a JNDI/LDAP lookup, or ESB messaging would work well. 如果您需要访问/提供远程依赖项,JNDI / LDAP查找或ESB消息传递将很好地工作。 For injecting your services/DAO's/datasources into your typical enterprise server code you'd be better off using one of the common DI frameworks like Google Guice or Spring. 要将服务/ DAO /数据源注入典型的企业服务器代码,最好使用常见的DI框架,如Google Guice或Spring。

There is no single 'best' solution in software design; 软件设计中没有单一的“最佳”解决方案; it's always a tradeoff. 它始终是一种权衡。

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

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