Spring declaration by multiple interfaces - spring

I have some architecture issue.
I have two different interfaces (IntefaceA, IntefaceB) and a class (MyClass), which implements these.
When I inject MyClass like this:
#Autowired
InterfaceA myClass;
I am not able to use implemented methods from InterfaceB.
My idea was to check with the instanceof MyClass, to be able to call the method from InterfaceB, but currently autowired object as InterfaceA is not a (sub)-type from MyClass.
if(myClass instanceof MyClass) {
InterfaceB myClassFromInterfaceB =(InterfaceB) myClass;
result= myClassFromInterfaceB.methodFromInterfaceB
}
How can I autowire one object in spring, which can call all methods from all interfaces, which will be implemented by this object?
It is only possible to declare two different objects ?

If the code may be changed, the cleanest way would be creating an interface that is composed of these two interfaces and making your implementation class derive from it.
Then you can declare your field to inject with this super interface as type :
#Autowired
InterfaceAandB myClass;
If the code cannot be changed, as alternative declare two fields to autowire in your bean and specify different interface types for each field.
It will result to a same object injected twice but referenced by two variable with different interfaces :
#Autowired
InterfaceA myA;
#Autowired
InterfaceB myB;

Related

Spring return dynamic instance based of String value

Java Spring question:
I have a interface MyInterface with one method
void exec (String str);
I have many implementation of MyInterface, say Oneimpl, anotherimpl yetanotherimpl...and so on and can keep adding new implementations.
how do I obtain an instance of a specific implementation using just the name of the implementing class passed as a STRING value , say "someRandomImpl"
The code should be dynamic and can provide a instance of new implementations without code change.
implements ApplicationContextAware
it will autowired ApplicationContext object
use the object like
context.getBean(beanName)
then you get the bean

Marker interface with Multiple implementations...!

I have a question regarding how to implement Marker interface through spring. I need to point my marker interface to its implemented classes. Itself marker interface dont have any of function declaration.
interface A {
/* No Method declaration */
}
#Component("c")
Class B implement A {
void function1(){ .. }
void function2(){ .. }
}
#Component("c")
Class C implement A {
void function3(){ .. }
void function4(){ .. }
}
Now Some where in my business Logic, i would like to use #Autowire though my interface to point any of one implementation.
#Autowired
#Qualifier("b")
A aB;
#Autowired
#Qualifier("c")
A aC;
It dont work. Will you please help to implement in correct way…! I was expecting thorugh reflection it should give me the list of method available in the implemented classes but it dont.
Added More Details
The only thing i would like to do is, I would like to reply IResponse to my business methods, instead of different tyoe. Its ok for me if i would have to #Authowired direct to implementation like
#Autowired
B aB;
but i thought if there is some way my IDE and Spring do some logic and when i #Autowired my interface towards implementation then it should be able to pick my Implementation class and should show me the business methods. Its not magic, when i am using qualified. I just want from spring to show me business methods through reflection.
What is the point of injecting A exactly? You probably expect Spring to do some kind of "magic" when it injects the dependency. It does not. I will simply inject the bean that you have required if it can inject it. In your case, the Qualifer value gives a hint as to which bean instance spring injects.
Except the typo (it's #Autowired, not #Autowire), this code should indeed inject B and C. But as you declared them as being A in your code you'll get a simple java.lang.Object basically. That's just a fundamental principle of Java that is strongly typed language.

INTERFACES or TARGET_CLASS: Which proxyMode should I choose?

I am looking for a way to store my object and it seems that the best approach is to use proxies. I found 2 annotation in the internet, which one should I use :
#Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
or
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS )
Moreover, is it true that the proxies is the best way to use than using #Component
#Scope("session") or using #SessionAttributes?
You'll need to understand what each of those annotations does to choose for yourself. See the javadoc, here. Continue for a more detailed explanation.
The first
#Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
creates
a JDK dynamic proxy implementing all interfaces exposed by the class of the target object
In other words, the proxy will be a subtype of the interfaces that the target object's class implements, but won't be a subclass of the target object's class itself.
Essentially Spring does the following
public class Example {
public static void main(String[] args) throws Exception {
Foo target = new Foo();
InvocationHandler proxyHandler = ... // some proxy specific logic, likely referencing the `target`
// works fine
Printable proxy = (Printable) Proxy.newProxyInstance(Example.class.getClassLoader(),
target.getClass().getInterfaces(), proxyHandler);
// not possible, ClassCastException
Foo foo = (Foo) proxy;
}
public static class Foo implements Printable {
#Override
public void print() {
}
}
public interface Printable {
void print();
}
}
The proxy returned won't be of type Foo and you therefore can't inject it into any targets of that type. For example, Spring will fail to inject it into a field like
#Autowired
private Foo foo;
but will successfully inject the proxy into a field like
#Autowired
private Printable printable;
All calls to the proxy will be handled by the InvocationHandler (which usually performs some use case specific logic then delegates to the target object).
The second annotation
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS )
creates
a class-based proxy (uses CGLIB).
In addition to interfaces, with CGLIB Spring will be able to create a proxy whose class is a subclass of the target's class. In essence, it does the following
Foo target = new Foo();
net.sf.cglib.proxy.Enhancer enhancer = new net.sf.cglib.proxy.Enhancer();
enhancer.setInterfaces(target.getClass().getInterfaces());
enhancer.setSuperclass(target.getClass());
net.sf.cglib.proxy.MethodInterceptor interceptor = ... // some proxy specific logic, likely referencing the `target`
enhancer.setCallback(interceptor);
// works fine
Foo proxy = (Foo) enhancer.create();
CGLIB creates a new class that is a subclass of Foo and instantiates it (invoking the constructor of Foo). All calls to the proxy will be intercepted by the provided callback (which usually performs some use case specific logic and then delegates to the target object).
Since the proxy class extends Foo, Spring can inject the proxy into a field (or constructor/method parameter) like
#Autowired
private Foo injectMe;
All this to say, if you're programming to interfaces, then ScopedProxyMode.INTERFACES will be sufficient. If you're not, then use ScopedProxyMode.TARGET_CLASS.
As for using #SessionAttributes, it is not an alternative to session scoped beans. Session attributes are just objects, they are not beans. They don't possess the full lifecycle, injection capabilities, proxying behavior that a bean may have.
If you want to store the whole bean in the session, use #Scope, otherwise use #SessionAttributes. In the case of using #Scope, if the class implements some interfaces then use INTERFACES proxy mode, if not use TARGET_CLASS.
Usually your service implements an interface, which allows the use of JDK proxies (INTERFACES mode). But if that is not the case then use TARGET_CLASS, which creates a CGLIB proxy.
Using INTERFACES should be used if possible and TARGET as last resort if the bean does not implement interfaces.
While going through a blog post provided in the comments above, I found a comment stating cons of interface-based proxies.
On the post, user Flemming Jønsson posted this:
Be careful with using interface-based proxies.
If you are using Spring Security or Spring Transactions you might experience oddities when using interface-based proxies.
E.g. if you have a bean T and that bean has methods a() and b() that are both annotated transactional. Calls from other beans directly to a() or b() will behave properly (as configured). However if you introduce an internal call - where a() calls b() then b's transactional metadata will have no effect. The reason is that when you are using interface-based proxies the internal call will not go through the proxy - and thus the transactional interceptor will not have a chance to start a new transaction.
The same goes for Security. If method a() only requires USER-role but calls b() that requires ADMIN-role, then the internal call from a to b will be performed for any USER with no warnings. Same reason as above, internal calls do not go through the proxy and thus the security interceptor does not have a chance to act upon the call to b() from a().
To solve issues like these use targetClass.

Using Singleton enum in Spring MVC

Here is my singlton class using enum:
public enum MyInstanceFactory {
INSTANCE;
private SOMEOBJECT;
private int countInitialization = 0;
private MyInstanceFactory(){
countInitialization++;
System.out.println("WOW!! This has been initialized: ["+countInitialization+"] times");
SOMEOBJECT = SOMETHING
}
public Session getSomeobject(){ return SOMEOBJECT; }
}
Now I am calling it like inside MVC controller
Session cqlSession = MyInstanceFactory.INSTANCE.getSomeobject();
In this way it calls constructer only first time and next and onwards it return the correct value for SOMEOBJECT.
My question is I want to do the same thing when a spring application start i.e. initializing contructor once and use **getSomeobject** multiple times.
I saw THIS SO ANSWER but here they are saying
If it finds a constructor with the right arguments, regardless of visibility, it will use reflection to set its constructor to be accessible.
Will reflection create problem for a singlton class?
If you need a non-subvertible singleton class (not just a singleton bean that's shared by many other beans, but actually a singleton class where the class can only ever be instantiated once), then the enum approach is a good one. Spring won't try to instantiate the enum itself, because that really makes no sense; that would be a much more extremely broken thing to do than merely calling a private constructor.
In that case, to refer to the enum instance from Spring configuration, you do the same thing as for any other static constant; for example:
<util:constant static-field="MyInstanceFactory.INSTANCE" />

Annotations for Java enum singleton

As Bloch states in Item 3 ("Enforce the singleton property with a private constructor or an enum type") of Effective Java 2nd Edition, a single-element enum type is the best way to implement a singleton. Unfortunately the old private constructor pattern is still very widespread and entrenched, to the point that many developers don't understand what I'm doing when I create enum singletons.
A simple // Enum Singleton comment above the class declaration helps, but it still leaves open the possibility that another programmer could come along later and add a second constant to the enum, breaking the singleton property. For all the problems that the private constructor approach has, in my opinion it is somewhat more self-documenting than an enum singleton.
I think what I need is an annotation which both states that the enum type is a singleton and ensures at compile-time that only one constant is ever added to the enum. Something like this:
#EnumSingleton // Annotation complains if > 1 enum element on EnumSingleton
public enum EnumSingleton {
INSTANCE;
}
Has anyone run across such an annotation for standard Java in public libraries anywhere? Or is what I'm asking for impossible under Java's current annotation system?
UPDATE
One workaround I'm using, at least until I decide to actually bother with rolling my own annotations, is to put #SuppressWarnings("UnusedDeclaration") directly in front of the INSTANCE field. It does a decent job of making the code look distinct from a straightforward enum type.
You can use something like this -
public class SingletonClass {
private SingletonClass() {
// block external instantiation
}
public static enum SingletonFactory {
INSTANCE {
public SingletonClass getInstance() {
return instance;
}
};
private static SingletonClass instance = new SingletonClass();
private SingletonFactory() {
}
public abstract SingletonClass getInstance();
}
}
And you can access in some other class as -
SingletonClass.SingletonFactory.INSTANCE.getInstance();
I'm not aware of such an annotation in public java libraries, but you can define yourself such a compile time annotation to be used for your projects. Of course, you need to write an annotation processor for it and invoke somehow APT (with ant or maven) to check your #EnumSingleton annoted enums at compile time for the intended structure.
Here is a resource on how to write and use compile time annotations.

Resources