My question: is there a way to use javax.inject (or any other Java injection framework) for a consumer of a Provider to use multiple implementations at runtime if the number of implementations is unknown at build time?
Some background on my need for this: I work on reusable frameworks which, for the most part, combine the use of a factory and a service locator to load implementations. Several of these seem like they could be reworked to use proper dependency injection, at least insofar as removing the service locator, but there are some that require loading all implementations found on the class path. This is achieved through a simple "multi-implementation" implementation which then loads the other implementations, saving the instances off in a collection and looping over them when the API is called.
I assume you are running on the Java SE platform (as opposed to a Java EE platform) in which case I would highly recommend HK2 (see https://hk2.java.net/2.2.0/). It has a lot of support for efficiently instantiating services and it is certainly the case that multiple implementations of the same contract can be available at runtime. Then at runtime there are a whole manner of mechanisms that you can use to choose which particular implementation will satisfy the dependency (i.e., service ranking or assisted injection etc)
For build time with hk2 you can create "inhabitant" files that describe services to the point where they can be satisfied at runtime without classloading all of them (only the one that is picked will be classloaded if you do it properly). This can be a huge performance boost at boot time of your application (if that sort of thing matters to you).
If you are running on a Java EE platform you can also use HK2, but you should then also give a long look at CDI. Both CDI and HK2 are implementations of JSR-330, and so both work with javax.inject API
So you basically have one implementation that delegates a call to an API method to all other implementations. you will need to inject this bean in all the dependencies you can do this in spring by giving this bean (this implementation instance) an id and then inject it using #Autowired #Qualifier("bean_id"). now for listing all implementations that can be done easily in spring by injecting an applicationContext into your delegate implementation and then querying the applicationContext for all beans implementing the API interface.
Related
I'm still learning about the Spring Framework and I'm trying to really get a good understanding of when and how to use Dependency Injection
Should all dependencies be managed via Interfaces?
Use interfaces for dependencies that expose an API of some sort and that have an implementation that may need to be swapped out (e.g. using mocks in unit tests). One common case is the DAO (data access object), which in Spring Data refers to as a Repository, which ties your data model to a persistence layer. Another common case is a Service which exposes operations on your domain model. Typically a Service will depend on the data access layer, so to unit test the service you will mock the DAO/repository. Another example is a third-party service; these are often only used by production systems, but must be simulated in development and testing environments. In this case, an interface is far superior to, say, embedding boolean flags in your code and hoping you don't have any logic errors.
The key thing to remember about managing dependencies is actually managing your use of the new keyword. Any time you use new, you are creating a dependency on an implementation. The goal of dependency injection is to separate how you use things you depend on with how you get them. You can depend on either an interface or a class, for a simple, obvious reason: Java supports subclassing. So even if you depend on a class instead of an interface, you might end up with a subclass. Spring framework actually does this automatically in many cases.
If you find yourself needing to create objects and you're not sure that you should depend on them, have your dependency injection framework give you a Factory for those objects. How this works is obviously framework-dependent, but all frameworks that I know of support factories. If you're not using a framework, you can still write factories and use them instead of using new all the time.
If you write a code without using spring IOC container, you have to write some factory classes to create objects and hook them up. For an example instance consider a service class which has a reference to the DAO instance. You have to write some initialization factory for the service class which guarantees a singleton access to the service class and makes sure that the service class is instantiated with an instance of DAO. Creating new instances everywhere in your code is not a good practice, hence factory pattern is used. But if you use Spring IOC container it will take care of all these things. Usually it creates singleton instances so you don't need to use new keyword in your code lending you to write more clear code. Your code is loosely coupled and more maintainable with this approach. If you have only one public constructor you can now have the liberty of doing a constructor injection, without using #Autowire invasive annotation with the new spring version.
There are three DI mechanisma used in spring as stated here. Out of the three constructor injection is recommended since it is more testable and does not lead to any invariant. Field injection using #Autowire is evil and not recommended since it is not testable solution.
Hope this helps. Happy coding.
I think my understanding of spring beans is a bit off.
I was working on my project and I was thinking about this situation.
Say I have class Foo
class Foo(){
public void doSomething(Object a , Object b){ // input parameters does not matter actually.
//do something
}
}
If I am using this class in another class like :
class Scheduler{
....
#Autowired
private Foo foo;
someMethod(){
foo.doSomeThind(a,b);
}
....
}
In the above case Instead of Autowiring the Foo, I can make doSomeThing static and directly use Foo.doSomeThing(a,b)
I was just wondering if there any advantage of creating a bean or if there any disadvantage of using static methods like this?
If they are same, When should I go for spring bean and when should do I simply use a static method?
Static methods are ok for small utility functions. The limitation of static code is that you can't change it's behavior without changing code itself.
Spring, on the other hand, gives you flexibility.
IoC. Your classes don't know about the exact implementation of their dependencies, they just rely on the API defined by interface. All connections are specified in configuration, that can be different for production/test/other.
Power of metaprogramming. You can change the behavior of your methods by merely marking them (via annotations of in xml). Thus, you can wrap method in transactions, make it asynchronous or scheduled, add custom AOP interceptors, etc.
Spring can instrument your POJO method to make it an endpoint to remote web service/RPC.
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/
Methods in Spring beans can benefit from dependency injection whereas static methods cannot. So, an ideal candidate for static method is the one that does things more or less independently and is not envisioned to ever need any other dependency (say a DAO or Service)
People use Spring not because of some narrow specific futures that cannot be replaced by static classes or DI or whatever. People use Spring because of a more abstracted features and ideas it provide out of the box.
Here is a nice quote from Someone`s blog:
Following are some of the major benefits offered by the Spring Framework:
Spring Enables POJO Programming. Spring enables programmers to develop enterprise-class applications using POJOs. With Spring, you are able to choose your own services and persistence framework. You program in POJOs and add enterprise services to them with configuration files. You build your program out of POJOs and configure it, and the rest is hidden from you.
Spring Provides Better Leverage. With Spring, more work can be done with each line of code. You code in a more fast way, and maintain less. There’s no transaction processing. Spring allows you to build configuration code to handle that. You don’t have to close the session to manage resources. You don’t have to do configuration on your own. Besides you are free to manage the exceptions at the most appropriate place not facing the necessity of managing them at this level as the exceptions are unchecked.
Dependency Injection Helps Testability. Spring greatly improves your testability through a design pattern called Dependency Injection (DI). DI lets you code a production dependency and a test dependency. Testing of a Spring based application is easy because all the related environment and dependent code is moved into the framework.
Inversion of Control Simplifies JDBC. JDBC applications are quite verbose and time-taking. What may help is a good abstraction layer. With Spring you can customize a default JDBC method with a query and an anonymous inner class to lessen much of the hard work.
Spring’s coherence. Spring is a combination of ideas into a coherent whole, along with an overall architectural vision to facilitate effective use, so it is much better to use Spring than create your own equivalent solution.
Basis on existing technologies. The spring framework is based on existing technologies like logging framework, ORM framework, Java EE, JDK timers, Quartz and other view related technologies.
During unit testing you have more flexibility using bean because you can easily mock your bean methods. However, that is not the same with static methods where you may have to resort to PowerMock (which I recommend you stay away from if you can).
It actually depends on the role of the component you are referring to: Is this feature:
An internal tooling: you can use static (you wouldn't wrap Math.abs or String.trim in a bean)
Or a module of the project: design it to be a bean/module-class (a DAO class is best modular to be able to change/mock it easily)
Globally, you should decide w.r.t your project design what are beans and what are not. I think many dev put too much stuff inside bean by default and forget that every bean is an public api that will be more difficult to maintain when refactoring (i.e. restrained visibility is a good thing).
In general, there are already several answers describing the advantages of using spring beans, so I won't develop on that. And also note that you don't need spring to use bean/module design. Then here are the main reasons not to use it:
type-safety: Spring bean are connected "only" at runtime. Not using it, you (can) get much more guaranties at compile time
It can be easier to track your code as there is no indirection due to IoC
You don't need the additional spring dependency/ies which get quite heavy
Obviously, the (3) is correct only if you don't use spring at all in your project/lib.
Also, The (1) and (2) really depend on how you code. And the most important is to have and maintain a clean, readable code. Spring provides a framework that forces you to follow some standard that many people like. I personally don't because of (1) and (2), but I have seen that in heterogeneous dev teams it is better to use it than nothing. So, if not using spring, you have to follow some strong coding guidelines.
First some background:
I'm working on some webapp prototype code based on Apache Sling which is OSGI based and runs on Apache Felix. I'm still relatively new to OSGI even though I think I've grasped most concepts by now. However, what puzzles me is that I haven't been able to find a "full" dependency injection (DI) framework. I've successfully employed rudimentary DI using Declarative Services (DS). But my understanding is that DS are used to reference -- how do I put this? -- OSGI registered services and components together. And for that it works fine, but I personally use DI frameworks like Guice to wire entire object graphs together and put objects on the correct scopes (think #RequestScoped or #SessionScoped for example). However, none of the OSGI specific frameworks I've looked at, seem to support this concept.
I've started reading about OSGI blueprints and iPOJO but these frameworks seem to be more concerned with wiring OSGI services together than with providing a full DI solution. I have to admit that I haven't done any samples yet, so my impression could be incorrect.
Being an extension to Guice, I've experimented with Peaberry, however I found documentation very hard to find, and while I got basic DI working, a lot of guice-servlet's advanced functionality (automatic injection into filters, servlets, etc) didn't work at all.
So, my questions are the following:
How do declarative services compare to "traditional" DI like Guice or Spring? Do they solve the same problem or are they geared towards different problems?
All OSGI specific solutions I've seen so far lack the concept of scopes for DI. For example, Guice + guice-servlet has request scoped dependencies which makes writing web applications really clean and easy. Did I just miss that in the docs or are these concerns not covered by any of these frameworks?
Are JSR 330 and OSGI based DI two different worlds? iPOJO for example brings its own annotations and Felix SCR Annotations seem to be an entirely different world.
Does anybody have experience with building OSGI based systems and DI? Maybe even some sample code on github?
Does anybody use different technologies like Guice and iPOJO together or is that just a crazy idea?
Sorry for the rather long question.
Any feedback is greatly appreciated.
Updates
Scoped injection: scoped injection is a useful mechanism to have objects from a specific lifecycle automatically injected. Think for example, some of your code relies on a Hibernate session object that is created as part of a servlet filter. By marking a dependency the container will automatically rebuild the object graph. Maybe there's just different approaches to that?
JSR 330 vs DS: from all your excellent answers I see that these are a two different things. That poses the question, how to deal with third party libraries and frameworks that use JSR 330 annotations when used in an OSGI context? What's a good approach? Running a JSR 330 container within the Bundle?
I appreciate all your answers, you've been very helpful!
Overall approach
The simplest way to have dependency injection with Apache Sling, and the one used throughout the codebase, is to use the maven-scr-plugin .
You can annotate your java classes and then at build time invoke the SCR plugin, either as a Maven plugin, or as an Ant task.
For instance, to register a servlet you could do the following:
#Component // signal that it's OSGI-managed
#Service(Servlet.class) // register as a Servlet service
public class SampleServlet implements Servlet {
#Reference SlingRepository repository; // get a reference to the repository
}
Specific answers
How do declarative services compare to "traditional" DI like Guice or Spring? Do they solve the same problem or are they geared towards different problems?
They solve the same problem - dependency injection. However (see below) they are also built to take into account dynamic systems where services can appear or disappear at any time.
All OSGI specific solutions I've seen so far lack the concept of scopes for DI. For example, Guice + guice-servlet has request scoped dependencies which makes writing web applications really clean and easy. Did I just miss that in the docs or are these concerns not covered by any of these frameworks?
I haven't seen any approach in the SCR world to add session-scoped or request-scoped services. However, SCR is a generic approach, and scoping can be handled at a more specific layer.
Since you're using Sling I think that there will be little need for session-scoped or request-scoped bindings since Sling has builtin objects for each request which are appropriately created for the current user.
One good example is the JCR session. It is automatically constructed with correct privileges and it is in practice a request-scoped DAO. The same goes for the Sling resourceResolver.
If you find yourself needing per-user work the simplest approach is to have services which receive a JCR Session or a Sling ResourceResolver and use those to perform the work you need. The results will be automatically adjusted for the privileges of the current user without any extra effort.
Are JSR 330 and OSGI based DI two different worlds? iPOJO for example brings its own annotations and Felix SCR Annotations seem to be an entirely different world.
Yes, they're different. You should keep in mind that although Spring and Guice are more mainstream, OSGi services are more complex and support more use cases. In OSGi bundles ( and implicitly services ) are free come and go at any time.
This means that when you have a component which depends on a service which just became unavailable your component is deactivated. Or when you receive a list of components ( for instance, Servlet implementations ) and one of them is deactivated, you are notified by that. To my knowledge, neither Spring nor Guice support this as their wirings are static.
That's a great deal of flexibility which OSGi gives you.
Does anybody have experience with building OSGI based systems and DI? Maybe even some sample code on github?
There's a large number of samples in the Sling Samples SVN repository . You should find most of what you need there.
Does anybody use different technologies like Guice and iPOJO together or is that just a crazy idea?
If you have frameworks which are configured with JSR 330 annotations it does make sense to configure them at runtime using Guice or Spring or whatever works for you. However, as Neil Bartlett has pointed out, this will not work cross-bundles.
I'd just like to add a little more information to Robert's excellent answer, particularly with regard to JSR330 and DS.
Declarative Services, Blueprint, iPOJO and the other OSGi "component models" are primarily intended for injecting OSGi services. These are slightly harder to handle than regular dependencies because they can come and go at any time, including in response to external events (e.g. network disconnected) or user actions (e.g. bundle removed). Therefore all these component models provide an additional lifecycle layer over pure dependency injection frameworks.
This is the main reason why the DS annotations are different from the JSR330 ones... the JSR330 ones don't provide enough semantics to deal with lifecycle. For example they say nothing about:
When should the dependency be injected?
What should we do when the dependency is not currently available (i.e., is it optional or mandatory)?
What should we do when a service we are using goes away?
Can we dynamically switch from one instance of a service to another?
etc...
Unfortunately because the component models are primarily focused on services -- that is, the linkages between bundles -- they are comparatively spartan with regard to wiring up dependencies inside the bundle (although Blueprint does offer some support for this).
There should be no problem using an existing DI framework for wiring up dependencies inside the bundle. For example I had a customer that used Guice to wire up the internal pieces of some Declarative Services components. However I tend to question the value of doing this, because if you need DI inside your bundle it suggests that your bundle may be too big and incoherent.
Note that it is very important NOT to use a traditional DI framework to wire up components between bundles. If the DI framework needs to access a class from another bundle then that other bundle must expose its implementation details, which breaks the encapsulation that we seek in OSGi.
I have some experience in building applications using Aries Blueprint. It has some very nice features regarding OSGi services and config admin support.
If you search for some great examples have a look at the code of Apache Karaf which uses blueprint for all of its wiring.
See http://svn.apache.org/repos/asf/karaf/
I also have some tutortials for Blueprint and Apache Karaf on my website:
http://www.liquid-reality.de/display/liquid/Karaf+Tutorials
In your environment with the embedded felix it will be a bit different as you do not have the management features of Karaf but you simply need to install the same bundles and it should work nicely.
I can recommend Bnd and if you use Eclipse IDE sepcially Bndtools as well. With that you can avoid describing DS in XML and use annotations instead. There is a special Reference annotation for DI. This one has also a filter where you can reference only a special subset of services.
I am using osgi and DI for current my project, I've choosed gemini blueprint because it is second version of SPRING DYNAMIC MODULES, Based on this information I suggest you to read Spring Dynamic Modules in Action. This book will help you to understand some parts and points how to build architecture and why is it good :)
Running into a similar architecture problem here - as Robert mentioned above in his answer:
If you find yourself needing per-user work the simplest approach is to
have services which receive a JCR Session or a Sling ResourceResolver
and use those to perform the work you need. The results will be
automatically adjusted for the privileges of the current user without
any extra effort.
Extrapolating from this (and what I am currently coding), one approach would be to add #param resourceResolver to any #Service methods so that you can pass the appropriately request-scoped object to be used down the execution chain.
Specifically we've got a XXXXService / XXXXDao layer, called from XXXXServlet / XXXXViewHelper / JSP equivalents. So managing all of these components via the OSGI #Service annotations, we can easily wire up the entire stack.
The downside here is that you need to litter your interface design with ResourceResolver or Sessions params.
Originally we tried to inject ResourceResolverFactory into the DAO layer, so that we could easily access the session at will via the factory. However, we are interacting with the session at multiple points in the hierarchy, and multiple times per request. This resulted in session-closed exceptions.
Is there a way to get at that per-request ResourceResolver reliably without having to pass it into every service method?
With request-scoped injection on the Service layers, you could instead just pass the ResourceResolver as a constructor arg & use an instance variable instead. Of course the downside here is you'd have to think about request-scope vs. prototype-scope service code and separate out accordingly.
This seems like it would be a common problem where you want to separate out concerns into service/dao code, leaving the JCR interactions in the DAO, analogous to Hibernate how can you easily get at the per-request Session to perform repo operataions?
My current project is leveraging Spring, and our architect has decided to let Spring manage Services, Repositories and Factory objects, but NOT domain objects. We are closely following domain driven design. The reasoning behind not using spring for domain objects is primarily that spring only allows static dependency injection. What i mean by static dependency injection is that dependencies are specified inside xml configuration and they get "frozen".
I maybe wrong, but my current understanding is that even though my domain only leverages interfaces to communicate with objects, but spring's xml configuration forces me to specify a concrete dependency. hence all the concrete dependencies have to be resolved at deployment time. Sometimes, this is not feasible. Most of our usecases are based on injecting a particular type based on the runtime data or a message received from an end user.
Most of our design is following command pattern. hence, when we recieve a command, we would like to construct our domain model and based on data received from a command, we inject particular set of types into our aggregate root object. Hence, due to lack of spring's ability to construct a domain model based on runtime data, we are forced to use static factory methods, builders and Factory patterns.
Can someone please advise if spring has a problem to the above scenario ?
I could use AOP to inject dependencies, but then i am not leveraging spring's infrastructure.
I suggest you read the section in the Spring docs concerning Using AspectJ to dependency inject domain objects with Spring.
It's interesting that you said "I could use AOP to inject dependencies, but then i am not leveraging spring's infrastructure, " considering that AOP is a core part of Spring's infrastructure. The two go very well together.
The above link allows you to have Spring's AOP transparently inject dependencies into domain objects that are creating without direct reference to the Spring infrastructure (e.g. using the new operator). It's very clever, but does require some deep-level classloading tinkering.
Spring's dependency injection/configuration is only meant for configuring low-level technical infrastructure, such as data sources, transaction management, remoting, servlet mount-points and so forth.
You use spring to route between technical APIs and your services, and inside those services you just write normal Java code. Keeping Spring away from your domain model and service implementations is a good thing. For a start , you don't want to tie your application's business logic to one framework or let low-level technical issues "leak" into your application domain model. Java code is much easier to modify in the IDE than spring's XML config, so keeping business logic in java let's you deliver new features more rapidly and maintain the application more easily. Java is much more expressive than spring's XML format so you can more clearly model domain concepts if you stick to plain Java.
Spring's dependency injection (and dependency injection in general) is basically for wiring together Services, Repositories and Factories, etc. It's not supposed to directly handle things that need to be done dynamically in response to commands, etc., which includes most stuff with domain objects. Instead, it provides control over how those things are done by allowing you to wire in the objects you want to use to do them.
I've been using spring for some time, but I always wondered how does it work, more specifically, how do they load and weave beans/classes marked only with an interface or #annotation.
For the xml declarations, it's easy to see how spring preprocesses my beans (they are declared in the xml context that spring reads), but for the classes marked only with annotations, I can't see how that works, since I don't pass any agent to the jvm or so.
I believe there is some Java/JVM hook that allows you to preprocess classes by some sort of criteria, but I wasn't able to found out anything on the docs.
Can someone point me to some docs? Is this related to the java.lang.instrument.ClassFileTransformer API?
Actually by default Spring does not
do any bytecode postprocessing
neither for XML-, nor
annotation-configured beans. Instead
relevant beans are wrapped into dynamic
proxies (see e.g.
java.lang.reflect.Proxy in the
Java SDK). Dynamic proxies wrap the
actual objects you use and intercept
method calls, allowing to apply AOP
advices. The difference is that proxies are essentially new artificial classes created by the framework, whereas weaving/bytecode postprocessing changes the existing ones. The latter is impossible without using the Instrumentation API you mentioned.
As for the annotations, the implementation of <context:component-scan> tag will scan the classpath for all classes with the Spring annotations and create Spring metadata placeholders for them. After that they are treated as if they were configured via XML (or to be more specific both are treated the same).
Although Spring doesn't do bytecode postprocessing itself you can configure the AspectJ weaving agent that should work just fine with Spring, if proxies do not satisfy you.