Using dependency injection in a library - java

I'm writing a java library that will be used by an existing application. I'm using dependency injection so testing is easier, and I'm familiar with Spring so I was planning to use it to manage the dependency injection while testing. The applications that will eventually use the library are not Spring-based, however, nor does it use any IoC/DI container of any sort currently. My question is, what's the best approach for injecting dependencies if Spring or Guice are not used? Should I consider something like a factory method to instantiate and wire the objects? The dependencies are all inside the library, so it doesn't seem appropriate to have the application instantiate each dependency to create the main object.

what's the best approach for injecting dependencies if Spring or Guice are not used?
If your library was written in a DI-friendly idiom. It should be fairly easy to use as a straitforward java API. Think of your past experience with spring. There are several libraries out there that fit perfectly with the spring model but were written before spring time. I don't see nothing bad with a new followed by a couple of setXX followed by a call to the real work method. Just be extra careful, since, among other things, your client can forget to call thouse init methods that spring reliably calls.
Should I consider something like a factory method to instantiate and wire the objects? The dependencies are all inside the library, so it doesn't seem appropriate to have the application instantiate each dependency to create the main object.
Let the client application decide that. You are providing a library. Let the API client wire its own objects. Provide an example. Later, that same example can be used to make the factory method on the client's domain. Maybe the client application has it's own way to configure itself, and it would be desirable if the API your library provides to be flexible enough to take advantage of that.
Or maybe you can include guice. The licence is Apache. Just like a whole piece of Java itself.

Related

Proper Class Construction: Using Multiple Hard Dependencies

I'm trying to integrate Single Responsibility Principle into my Java code by refactoring large classes (2000+ lines) into smaller, cohesive classes (~200 lines). However I'm confused how to properly reduce coupling between classes, since certain classes seem bound to be create multiple "hard dependencies" via the new keyword.
I'm using dependency injection via constructors primarily, followed by setter methods, or methods which accept the dependency as a parameter and use it amonst other logic within the method body (not just a simple this.val = val; setter.
IntelliJ's automatic refactoring instantiates this newly extracted class and passes (injects) it with a this reference to the LoadController. If I have to refactor a 2000 line class, of course this auto-instantiation + injection will occur each time I extract a new class out. The following LoadController is a JavaFX controller class for the program's main stage, which acts as the starting point for various features:
public class LoadController{
private final DBConnection dbConnection = new DBConnection(this);
private final UpdateLabels updateLabels = new UpdateLabels(this);
private final OpenCloseMenu openCloseMenu= new OpenCloseMenu (this);
private final CreateVBox createVBox= new CreateVBox (this, dbConnection);
private final ...
private final ...
}
Is this wrong? My understanding is that large, separate functions should be in their own class ... BUT some classes must have multiple hard dependencies like above, in order to "guide" the flow of logic between the use of various other classes.
If you are doing dependency injection into JavaFX controllers, you might want to look into using something like Gluon Ignite to assist you.
Gluon Ignite allows developers to use popular dependency injection frameworks in their JavaFX applications, including inside their FXML controllers. Gluon Ignite creates a common abstraction over several popular dependency injection frameworks
The injection framework you choose to use (e.g. Guice or Spring) will be responsible for creating the injectable components (e.g. you don't invoke new) and injecting the relevant references into your code, (e.g. you don't need to write dbConnection = <some value>). The injection framework will have extensive documentation and blog articles on how it works and how it may best be used, so full discussion of that is outside the scope of this answer.
An alternate to Gluon Ignite is afterburner.fx, which is similar but uses a small custom implementation for #Inject, so is more lightweight (and a little less powerful), then the more established dependency injection frameworks (very simple to use though).
This is just one option, there are other ways you can handle this, but seeing as you state that you wish to perform dependency injection with JavaFX, it seems to make sense of proven frameworks to do this rather than try to roll your own implementation.
some classes must have multiple hard dependencies like above, in order to "guide" the flow of logic between the use of various other classes.
Using something like Guice you provide a module that defines bindings between interface types and implementations. These bindings tell Guice how to construct the dependencies, so you don't need to hard code the dependencies in your classes. See the BillingModule in the Guice getting started guide for a module example. If you need multiple instances of injectable objects, you can use Providers in Guice. Spring has similar concepts, but different names.
Deciding on whether or not to use a dependency injection framework is a tradeoff between the work you would need to do if there was no injection framework vs the additional time and complexity of integrating the framework into your application. so the decision of whether or not to use one needs to be an architectural decision that you make, there is not a generic right or wrong answer for every application on whether use of such frameworks is justified.
I decide that using an injection framework is superfluous for my requirements, then I am not doing anything inherently incorrect by having multiple hard dependencies in some classes, as shown above?
Well the dependencies need to be defined somewhere. Either in an inferred or centralized location such as dependency injection systems use or local to given classes as you might determine from a traditional responsibility driven design approach. So you are not necessarily doing anything wrong by having hard dependencies. Abstract decoupling patterns such as dependency injection aren't always required.
The trick is determining what dependencies to have where and how to manage them. Often it is just obvious and falls out naturally from the problem domain, sometimes techniques such as CRC modeling can help structure dependencies.
Related article:
Inversion of Control Containers and the Dependency Injection pattern by Martin Fowler.
My assumption is that I can refactor my large classes into smaller, cohesive classes with some of these classes having multiple hard dependencies, using new.
Yes, you can certainly do that.
Can an injection framework be integrated later on in a project's life, rather than early on when it may not be required yet?
Yes it can. It will be a bit of work to do so, but if the application is well structured, not all that difficult. It is more difficult to go the other way and try to remove usage of a dependency injection framework from applications and libraries that are already based on it.
Related:
Passing Parameters JavaFX FXML

Can you give me a example of dependency injection without frameworks?

I want to reduce the coupling between two components, then I thought of dependency injection, but for a long time, I just use Spring to implement this. But now, I am working in a project which is not suitable to use this framwork(it is too heavy).
So can you give me an example to implement dependency injection for myself?
Dependency Injection is a pattern that can easily used without framework support. Some even prefer it without framework support, but at least, whether or not a framework is actually beneficial depends on the way you use such framework and the type and size of application you are building/maintaining.
Dependency injection is simply about injecting the dependencies into a component from the outside. The most common and advised way to do so is through constructor injection. This means that a class should specify all its dependencies as constructor arguments.
You should always design your code as if there is no DI framework at all; your application code should be oblivious to the existence of such framework. This means that you should never decorate your code with framework specific attributes. They pollute your code and cause a vendor lock-in. If the DI library you use requires the use of attributes, switch to a different library.
The use of dependency injection will 'bubble' throughout the application. This means that a class that applies the dependency injection pattern will move the responsibility of the creation of its dependencies up the call stack. This means that the consumer of that class now becomes responsible of creating its dependencies. But since that consumer should apply dependency injection as well, it means that it pushes the responsibility of creating the dependencies up again. When all classes apply the dependency injection pattern, it means that the complete object graph(s) need to be created in a single place in the application. This is actually a good thing. This place is called the composition root.
Again, you don't need to use a DI library (a.k.a. IoC container), and your application code should definitely not depend on it. You should apply the Dependency Injection pattern (and the SOLID principles) to make your application maintainable. A DI library can be used to make your composition root maintainable, but it should ONLY be used IF it makes the composition root more maintainable. Not using a DI library gives you complete compile-time support over the creation of your object graphs. Using a DI library will make you lose this compile-time support, so the advantages of its use should outweigh the disadvantage of losing compile-time support. Furthermore, you need to make sure that you can verify the building of your object graphs during application start-up or at least in a test suite. If your DI container makes this hard to impossible, switching your library or building your object graphs by hand might be a better option.
Why do you want to reinvent the wheel? Java has excellent CDI framework. Its lightweight and easy to use. For more info, see http://docs.oracle.com/javaee/6/tutorial/doc/giwhl.html

use of org.openide.filesystems instead of reflection

The project I am currently working on uses reflection to lookup beans and inject them into corresponding injection points. The project is also built on Spring. For some reason it has been bugging me to see all the reflection for a while.
Then I thought how about using org.openide.filesystems to represent the injections and injection points in an xml file which gets generated by AnnotationProcessors at compile time. This xml file could be loaded at runtime and all the dependencies injected at appropriate injection points.
While I know that I can just create an example implementation, I am afraid that I might be just trying reinvent the wheel, so I decided to post the question here. Why is that nobody objects to use and abuse of spring and reflection in Web Projects ?

creating reusable modules

I'm writing a big Red5 Java application for the web.
Red5 a Flash Media Server alternative that is java based and is written with the spring framework.
I want to have many versions of my application online, each with different behaviors and different classes enabled or disabled.
I'm looking for a way to convert my code into modules based code that will allow me to remove/add modules/features from the main application.
I know about OSGI http://www.springsource.org/osgi but it says that it needs a SpringSource dm server and I have no idea how it's gonna work together in red5 and it's seems very complicated to fully understand.
I don't have a good knowledge of spring framework in general, i work with it db-related and that's it. red5 uses it more extensively.
so can anyone please make any sense from this information ? is there something that can be done to divide my code to modules ?
any information regarding the issue would be greatly appreciated.
My preferred method of dealing with this kind of situation is Dependancy Injection (DI). Spring has a DI capability built in, for which a tutorial is easy to find online. However, Spring's DI is not as good, for many reasons, as that provided by Guice, which I would highly recommend. (The main advantage of Guice over Spring's DI in my opinion is type safety.)
DI is basically a mechanism for replacing class implementations at runtime. Rather than hard code dependancies into classes (by having a class construct other classes directly for example) you code them to have their dependant classes passed to them in their constructors. The DI framework will then pass the correct instances at runtime according to the configuration. Spring configuration can be done via annotations or an XML file, Guice uses a subclass of com.google.inject.AbstractModule.
So you could use different configuration files for the different instances of your application, and have them provide different sets of features for activation, or indeed different implementations of the same feature. If you set up the application to use this technique then the only thing that need differ between instances is a single configuration file.

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;
Dependency Injection
- some framework injects a required object into another object based on an external configuration, example: Spring managed beans
Dependency Lookup
- a class looks up a required dependency in some kind of directory service, example: JNDI lookups in a Java EE container
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()
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.
Static factories are similar to lookup services.
I prefer dependency injection.
When I talk about DI with Spring Framework I see following
It's supported by IDEs (error check, visualization).
You can setup other needed stuff like AOP, properties loading, ...
You have big config possibilities - XML, annotation, JavaConfig
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. If you need to access/provide a remote dependency, a JNDI/LDAP lookup, or ESB messaging would work well. For injecting your services/DAO's/datasources into your typical enterprise server code you'd be better off using one of the common D.I. frameworks like Google Guice or Spring.
There is no single 'best' solution in software design; it's always a tradeoff.

Categories

Resources