JPA2, JAX-RS: #PersistentContext, How to get EntityManager in a Facade constructor? - jpa

I have a JAX-RS web service that was generated by Netbeans. There are non-abstract facade classes for the service's endpoints. The persistence context is being injected into the non-abstract facade. Everything is working well and I see my data being returned to Fiddler.
We are using DTOs and I am implementing an assembler pattern. So, in the non-abstract facade's constructor, I am creating an instance of the assembler, and am passing the facade's entity manager instance into it. Unfortunately, it seems that the injection of the persistence context has not happened before the facade's constructor has been called, so I cannot pass the entity manager instance into the assembler for its to use in mapping operations. Kind of a chicken-before-the-end situation... I cannot figure out how to make this work... Is there some kind of post-constructor method that I can override and perform the initialization of the assembler and pass in the entity manager to it? I'd really appreciate your help and suggestions.
Thank you for your time and ideas,
Mike

Use method marked with #PostConstruct annotation. Like this:
#PostConstruct
private void init() {
// I'm called after all injections have been resolved
// initialize some object variables here
...
}
In that method you can use both, object fields initialized in the constructor and passed by injection.

Related

In Dagger, does an Inject annotated class also act as a Provider?

I am new to Dagger (version 2.16 on Android) and based on my reading so far, I understand that for a component, there should be a provider (#Provides or #Binds) encapsulated in a module (#Module). Going through a lot of samples, I see code which has some objects which are not offered in any Module, nor are they being instantiated using new.
It is also my understanding that in order to access the dependencies in a module, a consumer class needs to inject itself in the component graph (components usually offer a method to inject classes). The code examples are not doing this either.
Here's some code demonstrating both my concerns. RecipePresenter is not being provided in any module, but still RecipeActivity is using it.
A possible explanation I could think of is that #Inject, in addition to requesting the dependency also adds/injects the requesting class (RecipePresenter in the linked code) into the component graph. But assuming there are multiple components/subcomponents, which component does the class using #Inject constructor gets attached to? If my understanding is correct, why do activities and fragments have to inject themselves manually in the component - shouldn't they be auto-injected if they declare a variable annotated with #Inject?
RecipePresenter has an #Inject-annotated constructor, which allows it to be provided. The #Inject annotation on the recipePresenter field within RecipeActivity does not help, just the #Inject-annotated constructor.
class RecipePresenter #Inject constructor(
private val useCase: RecipeUseCase,
private val res: StringRetriever) :
RecipeUseCase.Callback {
From the Dagger User's Guide:
Use #Inject to annotate the constructor that Dagger should use to create instances of a class. When a new instance is requested, Dagger will obtain the required parameters values and invoke this constructor.
If the class with the #Inject-annotated constructor also has a defined scope, then the binding will only affect components with the same scope annotation: An #ActivityScope class wouldn't be accessible from a #Singleton component, for instance. If the class has no scope defined, then the binding could appear on any and all components where it is needed, which is fine: The implementation is always the same, defined by the constructor itself.
#Inject has different meanings based on what it's annotating:
When you annotate a field with #Inject, it indicates that the DI system should set that field based on values from the DI system when it injects that object.
When you annotate a method with #Inject, it indicates that the DI system should call that method with parameters based on values from the DI system when it injects that object.
When you annotate a constructor with #Inject, it indicates that the DI system is allowed to call that constructor in order to create that object (which triggers the field and method injection above). In that sense it does act like a built-in Provider.
In Dagger specifically, #Provides methods take precedence over #Inject constructors (if they both exist for the same class), and unlike in the JSR-330 spec Dagger requires an #Inject-annotated constructor even when no other constructors are present. From the Dagger User's Guide:
If your class has #Inject-annotated fields but no #Inject-annotated constructor, Dagger will inject those fields if requested, but will not create new instances. Add a no-argument constructor with the #Inject annotation to indicate that Dagger may create instances as well.
Classes that lack #Inject annotations cannot be constructed by Dagger.
Finally, to answer your question about why activities and fragments need to inject themselves: Android is allowed to reflectively create Activity/Fragment/View objects without Dagger's help or participation. This means that nothing triggers the field and method injection described above, until you call a members-injection method on the component that instructs Dagger to populate those fields and call those methods. Consequently, you should never see an #Inject-annotated constructor on Application, Activity, Service, Fragment, View, ContentProvider, and BroadcastReceiver subclasses in Android: Android will ignore the #Inject annotation, so you might as well take control over injection yourself, manually or through dagger.android.

In Jersey 2.X, a Feature is instantiated by HK2. How can I use Factories I've also added?

In the strange, strange dependency injection world of Jersey, you can include an AbstractBinder (but maybe not just a Binder) as one of the objects in the return value of your Application's getSingletons() method.
That AbstractBinder can then call various bind() methods from within its configure() method, which Jersey, but no other JAX-RS implementation, is guaranteed to call—and hence you can link implementations to interfaces, which lets you do a semblance of dependency injection from that point forward in your application. That is, once you've done that, then injection points within, say, your resource classes will be "filled" by the implementations you've bound.
(You can also do this with factory classes, so that you bind a particular factory method's return value to a contract it implements.)
OK, fine.
Jersey also lets you place a Class that implements Feature into the return value of your Application's getClasses() method. Fine. This Feature class will be instantiated by HK2 under the covers—make a mental note of that!—and its configure(FeatureContext) method will be called at some point. At that point, the Feature may register some additional stuff by calling FeatureContext#register() and handing it whatever it wants to register.
(Presumably this is all a fairly complicated façade on top of HK2's DynamicConfiguration machinery.)
Anyway, since a Feature is instantiated by HK2 (remember?), it follows that you can #Inject things into its constructor, or have injection points elsewhere in the class. That's cool! Then HK2 can draw upon all the services it knows of to fill those injection points. Very neat.
Ah, but the question is: what is the state of the HK2 world at this point? What services can be injected into a Feature implementation instantiated as part of A JAX-RS Application's startup sequence?
If your Application's getSingletons() method returns an AbstractBinder implementation that binds a FooImpl to Foo in Singleton scope in its configure() method, can your Feature—"registered" by including its class in the return value of your Application's getClasses() method—then inject a Foo?
I think it is important to have your Foo interface binding proxied, i.e:
new AbstractBinder() {
#Override
protected void configure() {
bind(Foo.class)
.proxy(true)
.to(FooImpl.class)
.in(Singleton.class);
}
}
then dependency injection will be insensitive to the instatination order.

How to call constructor with interface arguments when mocking a concrete class with Moq

I have the following class, which uses constructor injection:
public class Service : IService
{
public Service(IRepository repository, IProvider provider) { ... }
}
For most methods in this class, I simply create Moq mocks for IRepository and IProvider and construct the Service. However, there is one method in the class that calls several other methods in the same class. For testing this method, instead of testing all those methods together, I want to test that the method calls those methods correctly and processes their return values correctly.
The best way to do this is to mock Service. I've mocked concrete classes with Moq before without issue. I've even mocked concrete classes that require constructor arguments with Moq without issue. However, this is the first time I've needed to pass mocked arguments into the constructor for a mocked object. Naturally, I tried to do it this way:
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Mock<Service>(repository.Object, provider.Object);
However, that does not work. Instead, I get the following error:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: My.Namespace.Service.
Could not find a constructor that would match given arguments:
Castle.Proxies.IRepository
Castle.Proxies.IProvider
This works fine if Service's constructor takes simple arguments like ints and strings, but not if it takes interfaces that I'm mocking. How do you do this?
Why are you mocking the service you are testing? If you are wishing to test the implementation of the Service class (whether that be calls to mocked objects or not), all you need are mocks for the two interfaces, not the test class.
Instead of:
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Mock<Service>(repository.Object, provider.Object);
Shouldn't it be this instead?
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Service(repository.Object, provider.Object);
I realize that it is possible to mock concrete objects in some frameworks, but what is your intended purpose? The idea behind mocking something is to remove the actual implementation so that it does not influence your test. But in your question, you have stated that you wish to know that certain classes are called on properly, and then you wish to validate the results of those actions. That is undoubtedly testing the implementation, and for that reason, I am having a hard time seeing the goals of mocking the concrete object.
I had a very similar problem when my equivalent of Service had an internal constructor, so it was not visible to Moq.
I added
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
to my AssemblyInfo.cs file for the implementing project. Not sure if it is relevant, but I wanted to add a suggestion on the off chance that it helps you or someone else.
It must be old version issue, all is ok with latest version. Nick, Please check!
P.s.: I started bounty by misstake (I had wrong signature in my constructor).

How to debug Dependency Injection Bugs in Extbase?

I'm building an extension in Extbase (latest version, latest typo3) and am having repositories injected into my models.
This simply does not work. No errors, no clues, nothing. The inject* Method simply does not get called. The exact same Injection works in the controller.
Is it possible to inject Repositories into models in Extbase? In general, injection to models is possible since 1.4.
How can I debug this? Where do I have to look?
This is a common misconception:
Not every class you use in TYPO3 CMS uses dependency injection by default - and it's a good thing.
What is true, is that every object that has been instantiated by the ObjectManager can benefit from it.
In short: if you new Thing() some object, it won't benefit from dependency injection. If you use the ObjectManager to get an instance of something, the whole dependency injection gallore will rain down on your new instance:
constructor injection [Example: How can I use an injected object in the constructor?
annotations are read and field injections are done
setter injection was done in the past (Remark: I think it's deprecated)
public method (if existent) initializeObject is called
Note that injected objects are being instantiated by the objectManager as well-so recursion is possible if injected ServiceA needs an injected ServiceB.
Singletons are possible as well if you implement the marker interface SingletonInterface.
Dependency injection only works if you get an instance of the object via the ObjectManager. If you are using the good ol'
t3lib_div::makeInstance('Tx_yourextension_domain_model_thing')
inject* methods are not being called.
There is a german blog entry explaining how it works.

Creating new entities while enabling injection

I have a method on a stateless session bean which creates a new instance of an entity and persists it. You might normally use new MyEntity() to create the object but I would like injection to populate some of the properties of the entity for me.
I got partial success using
#Inject
#New
private MyEntity myNewEntity;
in the session bean and then using that instance in my method.
The problem I have now is that the second time the method is called, myNewEntity isn't a new object, its the same object as the one created the first time. As a result I'm getting
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '9' for key 'PRIMARY'
Or at least that's why I think I'm getting this exception. Certainly if I use new MyEntity() I don't get the exception but my injection doesn't happen.
Am I on the wrong track? How can I create a new local entity object while enabling injection?
Any help would be great!
First of all - I have serious doubts that it's a good idea to use CDI to control the lifecycle of a Entity. See this quote from the documentation (here):
According to this definition, JPA
entities are technically managed
beans. However, entities have their
own special lifecycle, state and
identity model and are usually
instantiated by JPA or using new.
Therefore we don't recommend directly
injecting an entity class. We
especially recommend against assigning
a scope other than #Dependent to an
entity class, since JPA is not able to
persist injected CDI proxies.
What you should do to create new instances of entities is adding a layer of indirection, either with #Produces or #Unwraps (Seam Solder, if you need it to be truly stateless), and thereby making sure that you code explicitly calls new.
I think I have a working solution now which seems okay, though I'm not quite sure why it works so I welcome your feedback on a better solution. I am now injecting a DAO-style bean into my stateless session bean:
#Stateless
public class PhoneService {
#Inject
protected ProblemReports problemReports;
An injecting my entity into the ProblemReports bean:
public class ProblemReports {
#Inject
#New
private ProblemReport newProblemReport;
I assume that ProblemReports defaults to #Dependant scope which as I understand it should be the same as the stateless session bean which containts it. I could understand this if the scope of ProblemReports was shorter, causing a new instance of ProblemReport to be created when the new ProblemReports is created; but it isn't.
Is this just an example of EJB and CDI not playing well together?