I have a strange behaviour when autowiring
I have a similar code like this one, and it works
#Controller
public class Class1 {
#Autowired
private Class2 object2;
...
}
#Service
#Transactional
public class Class2{
...
}
The problem is that I need that the Class2 implements an interface so I've only changed the Class2 so it's now like:
#Controller
public class Class1 {
#Autowired
private Class2 object2;
...
}
#Service
#Transactional
public class Class2 implements IServiceReference<Class3, Long>{
...
}
public interface IServiceReference<T, PK extends Serializable> {
public T reference(PK id);
}
with this code I get a org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type for Class2.
It seems that #Transitional annotation is not compatible with the interface because if I remove the #Transitional annotation or the implements IServiceReference<Class3, Long> the problem disapears and the bean is injected (though I need to have both in this class). It also happens if I put the annotation #Transitional in the methods instead of in the Class.
I use Spring 3.0.2 if this helps.
Is not compatible the interface with the transactional method?
May it be a Spring bug?
The problem is that your Class1 needs a reference to IServiceReference and not the concrete reference of Class2
#Controller
public class Class1 {
#Autowired
private IServiceReference object2;
...
}
The reason this is that Spring is creating a dynamic proxy for classes that you marked #Transactional. Thus when Class2 is created its wrapped in a Proxy object that is obviously not of type Class2 but is of type IServiceReference.
If you want the behavior of using Class2 with proxy support you will have to turn on CGLIB
Read below:
From Springs Doc:
Spring AOP defaults to using standard
J2SE dynamic proxies for AOP proxies.
This enables any interface (or set of
interfaces) to be proxied.
Spring AOP can also use CGLIB proxies.
This is necessary to proxy classes,
rather than interfaces. CGLIB is used
by default if a business object does
not implement an interface. As it is
good practice to program to interfaces
rather than classes, business classes
normally will implement one or more
business interfaces. It is possible to
force the use of CGLIB, in those
(hopefully rare) cases where you need
to advise a method that is not
declared on an interface, or where you
need to pass a proxied object to a
method as a concrete type.
It is important to grasp the fact that
Spring AOP is proxy-based. See the
section entitled Section 6.6.1,
“Understanding AOP proxies” for a
thorough examination of exactly what
this implementation detail actually
means.
The Transactional annotation instructs Spring to generate proxy objects around the annotated beans, to implement the transactional semantics. The generated proxy will implement the same interfaces as the target bean. So if your target bean implements IServiceReference, then so will the generated proxy.
If the target bean has no implemented interfaces, then the generated proxy will instead be a subclass of the target bean type.
In your original example, the transactional proxy will be a subclass of Class2, because Class2 implemented no interfaces. When you changed Class2 to implement IServiceReference, the generated proxy no longer extended Class2, and instead implemented IServiceReference. This caused your ClassCastException.
The best approach to this situation is to remove the reference from Class1 to Class2, and instead talk to Class2 purely through its interfaces. Class2 can implement as many interfaces as you like, the proxy will implement all of them.
You can force Spring to generate subclass proxies regardless of the interfaces, but it's additional complexity, and I'd recommend against it.
You can force it to proxy by adding
#Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
also see this documentation.
Related
For one of my requirment i have created a inteface with multiple methods and each method annotated with my own java custom annotation.
I have a spring aop aspect for my implementation class and i am not able to get my custom annotation in aop aspect.
after doing debug i understood my custom annotation is part of the interface and not in implementation class.
How can i get my custom annotation in my implementation methods which declared in interface ?
In Java, annotations are not inhereted from interfaces.With aspects you must annotate the implementation class (and/or methods within that class), not the interface (if any) that the class implements. String aop follows Java’s rule that annotations on interfaces are not inherited.
So, if you want to work with your annotation , create an abstract super class to be able to do this.
Inside aspect you work with proxy object and methods are wrapped in proxy calls. But if you know a real class/interface , you can get annotation by reflection api from source class/interface
I have this technical doubt...
If I have an interface
public interface test{
#Transactional
public void mymethod();
}
and then I have my implementation
public class testImpl implements test{
#Override
public void mymethod(){
//..do something
}
}
Since I am using #Override, will my annotation #Transactional, #Lock or any other persist on my implementation? or will overriden by the interface method without adding any special behaviour from the annotation?
Best answer I have read on this matter:
See this link https://stackoverflow.com/a/5551597/3447634
COPY OF THAT ANSWER:
"It really all depends on your application architecture, in my opinion. It depends on how you are proxying your classes. If you have your app set to "proxy-target-class='true'" (in your application context, then your #Transactional information wont be picked up if you annotate the Interface.
Check out The Spring Docs -- "Tips" for more information.
Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the #Transactional annotation, as opposed to annotating interfaces. You certainly can place the #Transactional annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies (proxy-target-class="true") or the weaving-based aspect (mode="aspectj"), then the transaction settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly bad."
When we annotate a class as #Autowired, does it HAVE to be a interface or can it be a class?
All the examples of using Spring I have seen, use an interface and then implement it on a class. The interface type is then used to call a function on the Concrete class. Can we not just simply add #Autowired to a concrete class rather than an interface.
I know of the Programme to a interface analogy in JAVA, but if u are not depending on Polymorphism, then why to write an interface?
No, you don't have to use interfaces, this is completely fine as far as Spring is concerned:
#Service
public class FooService {
#Autowired
private FooDao fooDao;
}
or you can even go for construction injection:
#Service
public class FooService {
private final FooDao fooDao;
public FooService(FooDao fooDao) {
this.fooDao = fooDao;
}
}
Often interfaces are anachronic practice repeated by every subsequent generation. Don't use them if they are not required. And they aren't required if they will always have just one implementation or if you want to mock such a class (modern mocking frameworks mock classes without any problem).
There is also nothing wrong in injecting concrete classes, like FooDao in example above. It has some technical implications wrt. proxying, but nothing that can't be comprehended.
Technically #Autowired could be used for an implementation or an interface. Spring doesn't care about it. Injecting an interface is a design strategy.
#Autowired can also be used with a class instead of interface.
But, using interfaces would be a better practice , since it reduces hard coupling between the components.
I have two interfaces: InterfaceA, InterfaceB which are both implemented by a concrete class TheClass. These interfaces are autowired in other beans like
public class UserA { #Autowired InterfaceA iface;}
public class Framework { #Autowired InterfaceB iface;}
The InterfaceA is a user interface exposed to external while InterfaceB is internal one only used by framework itself. I do this in order to isolate at interface level
I expect they are all wired to the same class that is TheClass. However, Spring wires them to different instances of TheClass even it is a singleton bean. I can understand InterfaceA and InterfaceB are different types so namely it is legal that wiring to different TheClass instances. But one class implementing multiple interfaces is common in Java. How should I handle this case? Autowiring by name is a solution, however, I personally like by type, is there any way of achieving this in by type?
==============================================================================================
Sorry, it's my bad. I mistakenly created two ApplicationContext in my code. Then the UserA class gets TheClass bean from one ApplicationContext while Framework class gets from another.
Spring does return the same bean for different interfaces as long as they are implemented by the same bean.
The question from the title in code:
#Transactional (readonly = true)
public interface FooService {
void doSmth ();
}
public class FooServiceImpl implements FooService {
...
}
vs
public interface FooService {
void doSmth ();
}
#Transactional (readonly = true)
public class FooServiceImpl implements FooService {
...
}
From http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html
The Spring team's recommendation is that you only annotate concrete classes with the #Transactional annotation, as opposed to annotating interfaces. You certainly can place the #Transactional annotation on an interface (or an interface method), but this will only work as you would expect it to if you are using interface-based proxies. The fact that annotations are not inherited means that if you are using class-based proxies then the transaction settings will not be recognised by the class-based proxying infrastructure and the object will not be wrapped in a transactional proxy (which would be decidedly bad). So please do take the Spring team's advice and only annotate concrete classes (and the methods of concrete classes) with the #Transactional annotation.
Note: Since this mechanism is based on proxies, only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with #Transactional!
(Emphasis added to the first sentence, other emphasis from the original.)
Spring's recommendation is that you annotate the concrete implementations instead of an interface. It's not incorrect to use the annotation on an interface, it's just possible to misuse that feature and inadvertently bypass your #Transaction declaration.
If you've marked something transactional in an interface and then refer to one of its implementing classes elsewhere in spring, it's not quite obvious that the object that spring creates will not respect the #Transactional annotation.
In practice it looks something like this:
public class MyClass implements MyInterface {
private int x;
public void doSomethingNonTx() {}
#Transactional
public void toSomethingTx() {}
}
You can put them on the interface but be warn that transactions may not end up happening in some cases. See the second tip in Secion 10.5.6 of the Spring docs:
Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the #Transactional annotation, as opposed to annotating interfaces. You certainly can place the #Transactional annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies (proxy-target-class="true") or the weaving-based aspect (mode="aspectj"), then the transaction settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly bad.
I would recommend putting them on the implementation for this reason.
Also, to me, transactions seem like an implementation detail so they should be in the implementation class. Imagine having wrapper implementations for logging or test implementations (mocks) that don't need to be transactional.
Supporting #Transactional on the concrete classes:
I prefer to architect a solution in 3 sections generally: an API, an Implementation and a Web (if needed). I try my best to keep the API as light/simple/POJO as possible by minimizing dependencies. It's especially important if you play it in a distributed/integrated environment where you have to share the APIs a lot.
Putting #Transactional requires Spring libraries in the API section, which IMHO is not effective. So I prefer to add it in the Implementation where the transaction is running.
Putting it on the interface is fine as long all foreseeable implementers of your IFC care about TX data (transactions aren't problems that just databases deal with). If the method doesn't care about TX (but you need to put it there for Hibernate or whatever), put it on the impl.
Also, it might be a bit better to place #Transactional on the methods in the interface:
public interface FooService {
#Transactional(readOnly = true)
void doSmth();
}