I am trying to convert a Guice inject project to a Java EE project, that is to run on glassfish.
I have a lib project, that defines an interface, Hello, annotated with #Remote. Then I have an impl project that has a bean, HelloBean, annotated with #Stateless, and a single constructor with parameters and #Inject.
Then I have a was project that depends on the lib and it's interface to create a webservice, HelloService, annotated with #WebService, and Hello as a member annotated with #EJB.
This does not seem to work. Since beans must have a no-args constructor, I created HelloBean as a bean, and HelloImpl as a Pojo with a single #Inject constructor, with arguments. I have tried then injecting Hello and HelloImpl into HelloBean with both #Inject, #Resource and #EJB. None seem to work.
If I #Inject Hello or HelloImpl into HelloBean, I get a NPE.
If I #Resource Hello or HelloImpl, I get an Lookup failed for delegate.
If I #EJB HelloImpl, same error. #EJB Hello and I get stackoverflows (understandably).
I do want to use constructor injection, as I feel it's a more correct way of creating classes (they are always valid once constructed). But I don't see how it's possible to combine CDI and EJBs.
How can I get a Pojo with an #Inject constructor into a bean? Or is my plan fundamentally flawed?
A better way is to define a initialize method annotated with #Inject. Any parameters will be injection points and should be supplied via CDI. You can also do this with constructors. Make sure you have WEB-INF/beans.xml as well.
Related
I have few beans which needs to be initialized either parallely or eagerly and to do this while reading the docs of micronaut, I noticed #Parallel annotation which can be used to initialize beans parallely and I came across #Context annotation which I am not able to understand clearly.
As for as my understanding is concerned, #Parallel annotation will shutdown the application if any of the beans executing simultaneously fails whereas #Context will not even startup the application if there is any failure.
I just wanted to check if this correct? Also, if I want to do eager initialization of bean rather than on-demand which annotation is the best one to use?
Any help appreciated, thanks in advance!
When you annotate a bean using the Context annotation, it simply means that the bean gets initialised earlier and eagerly (with the Application Context) than beans annotated with e.g. Singleton or Prototype.
Context scope indicates that the bean will be created at the same time as the ApplicationContext (eager initialisation)
With these annotations you define the scope of your bean within the application context.
Parallel does not define a bean scope, but as you found out yourself behaves accordingly to Context.
As a rule of thumb: If you have beans that need to start early, with the application context, annotate them using #Context.
If you have a singleton bean with a slow startup path declare it with #Singleton and #Parallel.
This is how I understud the documentation.
Baeldung has this section:
this limits matching to join points where the bean reference is an
instance of the given type, while target limits matching to join
points where the target object is an instance of the given type. The
former works when Spring AOP creates a CGLIB-based proxy, and the
latter is used when a JDK-based proxy is created. Suppose that the
target class implements an interface:
public class FooDao implements BarDao {
...
}
In this case, Spring AOP will use the JDK-based proxy, and we should
use the target PCD because the proxied object will be an instance of
the Proxy class and implement the BarDao interface:
#Pointcut("target(com.baeldung.pointcutadvice.dao.BarDao)")
On the other hand, if FooDao doesn't implement any interface, or the
proxyTargetClass property is set to true, then the proxied object will
be a subclass of FooDao and we can use the this PCD:
#Pointcut("this(com.baeldung.pointcutadvice.dao.FooDao)")
I'm still confuse why this just works with CGLIB proxy and target just works with JDK proxy. Could you help to tell me the different between them?
Actually, the explanation in the tutorial does not make much sense:
Both this(MyInterface) and target(MyInterface) work for JDK proxies, if the bean is declared as a MyInterface type.
Both this(MyClass) and target(MyClass) work for CGLIB proxies, if the bean is declared as a MyClass type.
Just try, and you will see that I am right. In Spring AOP, there is not real difference between this() and target(), because due to its proxy-based nature, it implicitly only supports execution() pointcuts from AspectJ.
In native AspectJ however, you also have other pointcut types such as call(), and there you would see a difference: this() would match the caller's type, while target() would match the callee's type. E.g., if you intercept a method A.a() calling B.b() via pointcut call(B.b()), this() would return an A instance, while target() would return a B instance. Do not worry, if this is difficult to understand for you, because for Spring AOP and execution pointcuts it really does not matter.
The only subtle difference I noticed in Spring AOP is, that for MyInterfaceImpl implements MyInterface, pointcut target(MyInterfaceImpl) would actually match, while this(MyInterfaceImpl) would not. This is because for JDK proxies, the proxy actually extends java.lang.reflect.Proxy, not MyInterfaceImpl. The proxy only delegates to a MyInterfaceImpl instance.
Edit: If you keep in mind that, in contrast to native AspectJ which involves no dynamic proxies, the semantics in Spring AOP are such that
this() relates to the proxy object, while
target() relates to the proxied object (proxy target),
it becomes clear why in this special case for JDK proxies target() matches, but this() does not.
Reference: Spring manual, section "Declaring a pointcut - examples":
this(com.xyz.service.AccountService): Any join point (method execution only in Spring AOP) where the proxy implements the AccountService interface.
target(com.xyz.service.AccountService): Any join point (method execution only in Spring AOP) where the target object implements the AccountService interface.
Only in this case, we are not asking for the interface class (which both the proxy and the target object implement), but for the implementation class itself.
Bottom line: For all intents and purposes, in normal use cases you can use either this() or target() for both JDK and CGLIB proxies. I recommend to stick with target(), because it best matches the implicit execution() semantics of Spring AOP, and usually you are interested in information about the target rather than about the proxy..
I've read what the annotation says but I'm kinda dumb, so couldn't understand propertly
Identifies injectable constructors, methods, and fields. May apply to static as well as instance members. An injectable member may have any access modifier (private, package-private, protected, public). Constructors are injected first, followed by fields, and then methods. Fields and methods in superclasses are injected before those in subclasses. Ordering of injection among fields and among methods in the same class is not specified.
Can you explain me what is #Inject for? If it is possible with a real life analogy with something less abstract
#Inject is a Java annotation for describing the dependencies of a class that is part of Java EE (now called Jakarta EE). It is part of CDI (Contexts and Dependency Injection) which is a standard dependency injection framework included in Java EE 6 and higher.
The most notorious feature of CDI is that it allows you to inject dependencies in client classes. What do I mean by dependencies? It is basically what your class needs to do whatever it needs to do.
Let me give you an example so that it is easier to understand. Imagine that you have a class NotificationService that is supposed to send notifications to people in different formats (in this case, email and sms). For this, you would most probably like to delegate the actual act of sending the notifications to specialized classes capable of handling each format (let's assume EmailSender and SmsSender). What #Inject allows you to do is to define injection points in the NotificationService class. In the example below, #Inject instructs CDI to inject an EmailSender and SmsSender implementation objects via the constructor.
public class NotificationService {
private EmailSender emailSender;
private SmsSender smsSender;
#Inject
public NotificationService(EmailSender emailSender, SmsSender smsSender) {
this.emailSender = emailSender;
this.smsSender = smsSender;
}
}
It is also possible to inject an instance of a class in fields (field injection) and setters (setter injection), not only as depicted above in constructors.
One of the most famous JVM frameworks taking advantage of this dependency injection concept is Spring.
I included a library I'd like to use, but in accessing to one of its classes I get the error message,
"Cannot access '<init>': it is private in [class name]
Is there something I can do to rectify this on my side, or am I just stuck to not use the package?
The error means the constructor is private. Given your comment, I'm assuming you're using a library. If this is the case, you'll have to find a different way to initialize it. Some libraries have factories or builders for classes, so look up any applicable documentation (if it is a library or framework). Others also use the singleton pattern, or other forms of initialization where you, the developer, don't use the constructor directly.
If, however, it is your code, remove private from the constructor(s). If it's internal and you're trying to access it outside the module, remove internal. Remember, the default accessibility is public. Alternatively, you can use the builder pattern, factory pattern, or anything similar yourself if you want to keep the constructor private or internal.
I came across this issue when trying to extend a sealed class in another file. Without seeing the library code it is hard to know if that is also what you are attempting to do.
The sealed classes have the following unique features:
A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class itself.
A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.
Sealed classes are not allowed to have non-private constructors (their constructors are private by default).
Classes that extend subclasses of a sealed class (indirect inheritors) can be placed anywhere, not necessarily in the same file.
For more info, have a read at https://www.ericdecanini.com/2019/10/14/kotlins-sealed-class-enums-on-steroids/
Hopefully, this will help others new to Kotlin who are also encountering this issue.
Class constructors are package-private by default. Just add the public keyword before declaring the constructor.
By default constructor is public so need to remove internal keyword.
We are implementing IoC/DI in our application using NInject framework. We are having internal classes having internal methods. To implement IoC/DI, we have to extract interfaces. But if we are having only internal methods in an internal class, we can't extract interface for that class.
So is there a way to implement IoC/DI in such cases (internal class having only internal methods) or should we change our internal methods to public methods. Kindly suggest. Thanks
If your class is already internal then there is absolutely not difference between internal and public methods. public methods of internal classes are only internally visible.
If you stay with injecting concrete classes though you loose all the advantages of DI. So yes you should extract (internal) interfaces and inject the interfaces. This requires that the configuration code has access to the classes by either beeing in the same assembly of the assembly must be declased as friend assembly. Futhermore, you have to configure Ninject to allow none public classes. See NinjectSettings.
The only thing that you really need to make public is the interface (not the concrete implementation).
You can use an abstract factory or (easier) Ninject to map the public interface to the internal concrete; thus your client code just has to request an instance of "a thing" that implements the interface and your factory / container will return the implementation.
You should read up on Dependency Inversion Principle as well as it goes hand-in-hand with this.
You could use InternalsVisibleTo attribute in AssemblyInfo.cs file like this
[assembly: InternalsVisibleTo("Assembly_That_Should_Access_The_Internal_Class")]