How to choose between dependency generation methods?

I have seen at least three ways to get dependencies in a Java object without associating the object with creating the dependency;

Dependency Injection - some structure embeds the required object into another object based on the external configuration, for example: Spring managed beans

Dependency search - the class searches for the required dependency in any directory service, for example: JNDI requests in the Java EE container

Static plants β€” an object in the global scope provides instances on demand β€” the standard Java SE APIs are dotted with these examples: java.util.Logger.getLogger (name) , java.util.Calendar.getInstance ()

What guidance can you indicate regarding the most appropriate for the situation?

+4
source share
3 answers

I prefer dependency injection because the object does not need to know how it gets the links it needs.

Dependency search still requires the object to know about the search service and its URL.

Static plants are similar to search services.

+6
source

I prefer dependency injection.

When I talk about DI with Spring Framework, I see the following

  • It is supported by the IDE (error checking, visualization).
  • You can configure other necessary things such as AOP, loading properties, ...
  • You have great configuration options - XML, annotation, JavaConfig
  • It can be used in a desktop application.

These redistributions of all negatives are like dependency on another library. Why should I use a different approach?

+2
source

It really depends on the context. If you are writing a stand-alone Maths API, you can use static factories because the code will be less verbose, without installation, and possibly more efficient. If you need to access / provide remote dependency, JNDI / LDAP search or ESB messaging will work well. To enter your services / DAO / data sources into your typical corporate server code, you would be better off using one of the common DIs like Google Guice or Spring.

There is no single β€œbest” solution in software development; it is always a compromise.

+1
source

All Articles