OSGI: DS and component factories issues - java

What I need is to get new instance of service every time when some consumer needs this service + using CDI. I've read a lot of articles and I can't find the answer to 2 my questions.
If we use factories, why in service consumer we call factory (http://www.rpgnextgen.com/wiki/doku.php?id=component_factory ) and after that we get reference to service. I mean
// get factory
ComponentFactory factory = (ComponentFactory) context.getService(serviceReferences[0]);
// get instance
ComponentInstance instance = factory.newInstance(null);
Is there no way to set factory with certain interface and in service consumer call service when osgi inside calls the factory?
If in service consumer we call factory then why we mark service as component when de facto factory is component?
The problem is that without factory I do #Inject #OsgiService (javase) or#OSGiService (javaee) and I can use different filters and code is very clear. Using component factory I (as I understand) loose this ability.

ComponentFactory exists for consumers that want to use a factory, because they want to control the lifecycle of the individual components. For example, if they want to create an instance of the component for every web request.
If you don't want to use ComponentFactory... then don't.

I need for every consumer new instance of component.
I haven't tried yet, but according to the documentation when using PAX-CDI and an OSGi v6 container then the prototype scope should do what you need:
#OsgiServiceProvider
#PrototypeScoped
public class MyService implements SomeService{

OSGi services in are special types of beans in CDI. Compare them to EJBs, you can use CDI to inject references to the different types of EJBs, but the components will have their own lifecycle. The same goes for OSGi services; their life cycle is not controlled by CDI. CDI just injects references to those services.
This means CDI factories can't be used with OSGi services. Just like you can't use CDI factories with EJBs. There is not really a way to create an OSGi service instance per injection point, so there's no workaround either.
If you require this kind of model: You have to create a factory mechanism yourself.

Related

EJBObject shared among clients?

Head first EJB states that in the case of stateless session beans:
Clients don't share EJBObject, but the same bean can serve multiple
EJBObjects
I don't see any reason why a single EJBObject cannot serve multiple clients.
Furthermore, if what the book states is correct, what is the advantage we get from pooling beans if we have to create one EJBObject per client ?
First of all, one has to understand what an EJBObject is:
The EJBObject interface is extended by all enterprise beans' remote interfaces. An enterprise bean's remote interface provides the remote client view of an EJB object. An enterprise bean's remote interface defines the business methods callable by a remote client.
With that being cleared, consider the following local EJB example:
public class SomeClass {
#EJB
private SomeBean someBean;
...
}
Basically, our EJBObject is nothing more than an attribute of our class SomeClass which references the EJB SomeBean.
What's happening is that, on the container's point of view, he's not really creating and injecting a dedicated instance of the EJB SomeBean. Instead, he's instantiating the EJB SomeBean, storing it in his EJB pool, creating a proxy for this instance and injecting the proxy in on our class SomeClass.
Therefore, for each client, you have a single EJBObject or proxy but, under the hood, as the Head First states, the same bean can serve multiple EJBObjects.
...what is the advantage we get from pooling beans if we have to create one EJBObject per client?
Well, for instance, thread-safety: if you have several instances of SomeClass, calling concurrently the same method of someBean, it is guaranteed that those calls will never be delegated to the same instance since Stateless session instances are dedicated to an EJB object only for the duration of a single method call.
Other advantages of EJB pooling can be found on this answer by Will Hartung. :)

How to stop Wicket creating multiple instances of Guice-injected singletons?

I'm a new Guice user, having been a long-time user of Spring IoC. I have a number of #Singleton classes for my service tier, which I understand is roughly equivalent to Spring's default bean scope.
However, when I am using #Inject in my Wicket pages a CGLib proxy of the target objects is created each time the page is constructed, thus creating new instances of my supposed-singletons.
Note that I'm injecting concrete classes, not interfaces.
How can I use #Inject and retrieve the single singleton instance of my Guice-injected objects?
Updated: Solution as per Sven's accepted answer
Inject interfaces in Wicket components rather than concrete classes. Despite much discussion on the subject in the linked thread, this appear to be the only practical solution.
The following issue gives some background:
https://issues.apache.org/jira/browse/WICKET-1130

Java EE 6 CDI injecting provider

I have doubts on when to inject the provider of an interface and when to inject an interface directly.
What is the appropriate situation where a provider should be used? Please give examples.
If the scope of an interface is #Dependant, then the injector will create a new object anyway, if so then do we still need to use a provider?
If #New is used, a new object is created. Do we need a provider then?
One of the main reasons to use providers (you don't inject providers though) is to do some configuration of a class. Another good reason is if the class isn't available as a CDI bean.

Guice Injection into Business Layer of Java Web App

I have sucessfully used Guice to Inject Providers into the servlet portion of an existing java web application, however, I can't access the injectors through the business layer (non-servlet java classes) of the application.
I have read up on Injecting the Injector, but to me that seems more like a hack and in several places, including the Guice documentation, it says not to do that too much.
I guess my question is, Where do I bootstrap a java web app so that the non-servlet/filter classes have access to the injector created in the class I use to extend GuiceServletContextListener? Is there any way to make those classes injectable without injecting the injector?
Thank you and let me know if you need any clarification.
Edit:
I am attempting to do this with a simple logger, so far, in my
servlets, I call:
#Inject
private static org.slf4j.Logger log;
The injection is set up in MyLoggerModule as follows (which is in the
createInjector call with ServletModule) :
#Override
public void configure() {
bindListener(Matchers.any(), new SLF4JTypeListener()); // I
built my own SLF4JTypeListener...
}
This all works perfectly in the servlets, but the field injection does
not work when called by a class that is not a servlet or filter.
Guice doesn't intercept calls for new objects, so if your business layer isn't already using Guice to create the objects that need injection, it'll need modification to do so.
The injection only works when handled by Guice during injection. So starting from the base injector you've made, whatever is marked with #Inject which is needed for the instance you've requested will be provided by Guice as best it can, and in turn, during instanciation of those, further #Inject annotations will be filled in by providers and bindings until nothing new needs to be instanciated. From that point on however you are not going to get fields injected into servlets created outside Guice's injection, perhaps by calling new somewhere, which is likely what your Object Factory is doing.
You'll need to change your Object Factory to use providers instead of new. If you could edit these, it wouldn't be too hard to do since Guice can give you default providers for bindings.
So one way your business layer could be Guice aware is to have whatever is creating servlets first create an Injector and then request the servlets be created by the injector. If this means you'll have more than one injector, then yes, that will be a problem but only for the objects you want to be singletons. So you could make a factory pattern class for a singleton injector, or you could find where these classes (here typed bar) which are creating servlets themselves are created (in foo), and then start with the injector there (in foo) using one Guice injector to create those (bar type) classes and also modifying them (bar type) to request a provider for the servlets which they'll use instead of making calls for a new servlet.
Now that I think about this, it could be simple if it kind of only happens once or twice for 10-20 servlet types, or it could be complicated if there's some framework that defines totally flexible behavior for what gets newed up when and why.
Another option would be avoiding #Inject on fields at all times, as recommended. So now your servlets are taking in an org.slf4j.Logger as a construction parameter. The constructor is marked #Inject, and it assigns the parameter's value to the field. Then any place you're not using injection should break with an incorrect number of parameters at a new call. Fix these by figuring out how to either get the servlet provided here instead, or how to get a provider for the servlet into the class.
Not sure what you mean... if you inject objects in to your servlets/filters, those objects have their dependencies injected by Guice as well, and so on all the way down.
How are you creating the classes that you're trying to inject this logger in to? They must be created by Guice to be injected, which means no new.

Factory class vs Spring DI

As per my understanding both Factory class and Spring DI follows the Dependency injection. I mean in both the cases external entity is used to push the dependency. Right?
My question is which one i should go for between factory classes and Spring DI when my intention is just to get the objects . Assume i don't want any other features like aop, dao support etc. Only purpose is to get the objects either from Factory class or Spring DI. Which one is preferable.
on some site read this statement
DI loosely coupled and less intrusive in comparison to Factory classes
But could not get how spring DI loosely coupled and less intrusive than factory classes?
in both the cases we have to insert some kind of get object code in our core program .
Spring DI promotes loosely coupled code because the Spring container injects your dependencies based on configuration. If you are injecting interface implementations, you don't have to change code to change which specific implementation gets injected, unless you consider your configuration code, which many do.
If you use a Factory to create configured objects that are used by the rest of your code, you are writing code to create the objects, configure them, etc. If you want to change what the factory returns, you have to change actual code, which some would argue is a more intrusive change.
Typically Spring is used to configure how the various layers of your application are wired together. X service takes such and such DAO implementations, for example. That's application level organization. Lets say you have a scenario where want to create a button for every row in a list -- in that case you could use a factory to create the buttons. This scenario is based on a runtime situation where the GUI has different elements that you couldn't configure up front (because its based on the data), so DI makes less sense here.
EDIT - based on your comment questions, I think the primary point here is that you have to consider is that Spring is also an Inversion of Control container. That means you don't program in which components in your application go where. Without IoC, you might do something like
MyServiceImpl extends MyService {
Dao1 = new Dao1Impl(); // you programmatically configure which components go in here
Dao2 = new Dao2Impl();
....
}
instead you do something like
MyServiceImpl extends MyService {
public Dao1; // you haven't specified which components, only interfaces
public Dao2;
....
}
In the second code sample, Spring (or whatever you use) will inject the appropriate DAO instances for you. You have moved control of which components to use to a higher level. So IoC and DI go hand and hand, IoC promotes loose coupling because in your component definitions (i.e. interfaces) you only specify behavior.
In other words, IoC and DI are not necessary for loose coupling; you can have loose coupling with a Factory too
MyServiceImpl extends MyService {
public dao1
public dao2;
MyServiceImpl(){
dao1 = DaoFactory.getDao1();
...
}
....
}
here your service still only depends on DAO definitions and you use the factory to get implementations. The caveat is that your service is now coupled to the factory. You can make it more loose by passing a Factory into your constructor if you want....
Also, dont forget that Spring provides other useful functionalities, like its transaction management. That's incredibly helpful, even though you said for your app you don't need it.
But could not get how spring DI loosely coupled and less intrusive
than factory classes? in both the cases we have to insert some kind of
get object code in our core program .
Spring makes it less intrusive because it uses reflection to automatically "inject/create" the dependencies. Thus your code does not need a reference to a the factory.
Spring is generally used for "Singleton-like" object creation. People generally use custom factories for transient throw away object creation (like request objects).
In fact often times you will make Spring create and inject your custom factories (ie factory of a factory).

Categories

Resources