Spring Bean implementing multiple interfaces - java

I have a bean which implements two interfaces. The barebones code is as follows:
interface InterfaceA {
...
}
interface InterfaceB {
...
}
public class ClassC implements InterfaceA, InterfaceB {
...
}
In my AppConfig I am specifying the following:
#Bean(name = "InterfaceA")
public InterfaceA interfaceA() {
return new ClassC();
}
#Bean(name = "InterfaceB")
public InterfaceB interfaceB() {
return new ClassC();
}
And I use it so:
public class MyClass {
#Inject
private final InterfaceA a;
public MyClass(#Named("InterfaceA") InterfaceA a) {
this.a = a;
}
...
}
However, Spring complains that:
No qualifying bean of type
[com.example.InterfaceA] is
defined: expected single matching bean but found 2:
InterfaceA, InterfaceB
Similar question was asked and answered for EJB here but I could not find anything for Spring beans. Anybody know the reason?
The workaround is to introduce a new interface which extends both InterfaceA and InterfaceB and then let ClassC implement that. However, I am loath to change my design because of framework constraints.

Thank you for your excellent question.
In my case, I created an interface that extends both A and B:
public interface InterfaceC extends InterfaceA, InterfaceB {}
... and the common implementation implements the unified interface:
public class ClassC implements InterfaceC {
//...
}
This unified interface allows then to create a single bean:
#Bean
public InterfaceC implementationForAandB() {
return new ClassC();
}
The Spring framework is then able to inject or autowire the common implementation to dependencies expressed in terms of the primary interfaces:
public class MyClass {
#Inject
private final InterfaceA a;
#Inject
private final InterfaceB b;
public MyClass(InterfaceA a, InterfaceB b) {
//...
}
}

Spring is right ... When you write
#Bean(name = "InterfaceA")
public InterfaceA interfaceA() {
return new ClassC();
}
#Bean(name = "InterfaceB")
public InterfaceB interfaceB() {
return new ClassC();
}
Spring creates to ClassC objects, one named InterfaceA, the other InterfaceB, both implementing InterfaceA and InterfaceB.
Then when you write :
#Inject
private final InterfaceA a;
you ask Spring to find a bean implementing InterfaceA, but as said above there are 2 so the error.
You could either create only one object of type ClassC, or use #Qualifier or #Named annotations :
#Inject
#Named("InterfaceA")
private final InterfaceA a;
That way, you explicitely ask Spring to find the bean named InterfaceA, and hopefuly it is now unique.

Related

Spring inject interface implementation

I'd like to use lombok to inject a class implemented from a interface like below:
#RequiredArgsConstructor(onConstructor = #_(#Inject))
public class className {
#NonNull
private final ClassA1 a1 implements ClassA;
...
}
But obviously this is not working, so what's the correct way to do this?
=================
edit:
Or should I do this way?
public class className {
private ClassA a1;
public className(A1 a1) {
this.a1 = a1; }
}
===================
Here's the code after taking advice from Mykhailo Moskura:
#Component
#RequiredArgsConstructor(onConstructor = #_(#Inject))
public class C {
#NonNull
private A b;
public someFunction() {
b.method();
}
}
Here A is the interface, while b is Class implementing A with camelcase name. And using lombok I injected b, and now call some method of b in some function. However I realized b.method still points to the interface A, but not B.
#NonNull is not required
Lombok will generate a constructor with fields that are marked as final or #NonNull
You can autowire just declaring the interface type
and giving the implementation class name in camel case starting from lower case.
Also you need to declare your implementation as bran and the class in which you are injecting it too.
#Inject is java ee CDI dependency.
#Autowired is spring specific.
Spring supports both but it says to use #Autowired
Here is an example:
public interface A{
}
#Component
public class B implements A{
}
#Component
public class C {
private A a;
#Autowired
public C(A a){
this.a = a;
}
}
Lombok sample:
#RequiredArgsConstructor
#Component
public class C {
//Here it will inject the implementation of A interface with name of implementation (As we have name of impl B we declare field as b , if HelloBeanImpl then helloBeanImpl
private A b;
}
But if you have many implementations of one interface you can use #Qualifier with name of bean or the above sample with lombok where A b where b is the name of implementation

Spring injected beans null in nested class

I have a class with 2 static nested classes that do the same operation on 2 different generic types.
I exposed the 2 classes as beans and added #Autowired for the constructors as I usually do.
Here is the basic setup
abstract class <T> Parent implements MyInterface<T> {
private final Service service;
Parent(Service service){ this.service = service; }
#Override public final void doInterfaceThing(T thing){
T correctedT = map(thing);
service.doTheThing(correctedT);
}
protected abstract T map(T t);
#Service
public static class ImplA extends Parent<A> {
#Autowired ImplA (Service service){ super(service); }
A map(A a){ //map a }
}
#Service
public static class ImplB extends Parent<B> {
#Autowired ImplB (Service service){ super(service); }
B map(B b){ //map b }
}
}
And in another class I have
#Service
public class Doer {
private final List<MyInterface<A>> aImpls;
#Autowired public Doer(List<MyInterface<A>> aImpls){ this.aImpls = aImpls; }
public void doImportantThingWithA(A a){
aImpls.get(0).doInterfaceThing(a);
}
}
When I run the app, everything appears to be injected correctly and when I put a breakpoint in the ImplA and ImplB constructors, I have a not-null value for "service". I also have an ImplA bean in the aImpls list in Doer.
When I call doImportantThingWithA(a) however, "service" is null inside ImplA and I obviously die.
I'm not sure how this is possible because:
I see a nonnull value in my constructors for service which is a final field.
If spring is injecting ImplA and ImplB into another class, it should already have either injected a Service into ImplA or ImplB, or thrown an exception on bean initialization. I have nothing set to lazily load and all bean dependencies are required.
The reason for the nested classes is because the only thing that changes between the 2 implementations is the map() function. Trying to avoid extra classes for 1 line of varying code.
More info:
When I add a breakpoint in Parent.doInterfaceThing(), if I add a watch on "service" I get null as the value. If I add a getService() method, and then call getService() instead of referring directly to this.service, I get the correct bean for service. I don't know the implications of this but something seems weird with the proxying.
It looks like what is causing the issue is Parent.doInterfaceThing();
If I remove final from the method signature, "service" field is correctly populated and the code works as expected.
I don't understand at all why changing a method signature affects the injected value of final fields in my class... but it works now.
What I meant with my "use mappers" comment was something like this:
class MyInterfaceImpl implements MyInterface {
#Autowired
private final Service service;
#Override public final <T> void doInterfaceThing(T thing, UnaryOperator<T> mapper){
T correctedT = mapper.apply(thing);
service.doTheThing(correctedT);
}
// new interface to allow autowiring despite type erasure
public interface MapperA extends UnaryOperator<A> {
public A map(A toMap);
default A apply(A a){ map(a); }
}
#Component
static class AMapper implements MapperA {
public A map(A a) { // ... }
}
public interface MapperB extends UnaryOperator<B> {
public B map(B toMap);
default B apply(B b){ map(b); }
}
#Component
static class BMapper implements MapperB {
public B map(B a) { // ... }
}
}
This does have a few more lines than the original, but not much; however, you do have a better Separation of Concern. I do wonder how autowiring works in your code with the generics, it does look as if that might cause problems.
Your client would look like this:
#Service
public class Doer {
private final List<MapperA> aMappers;
private final MyInterface myInterface;
#Autowired public Doer(MyInterface if, List<MapperA> mappers){
this.myInterface = if;
this.aImpls = mappers; }
public void doImportantThingWithA(A a){
aMappers.stream().map(m -> m.map(a)).forEach(myInterface::doInterfaceThing);
}
}

Spring - Inject proper service implementation in abstract class level autowired field

I have 2 class hierarchies:
* ClassA
* ClassB
* AbstractClass
* Class1
* ...
* Class5
AbstractClass autowires ClassA as follows:
public abstract class AbstractClass {
#Autowired
protected ClassA classA;
}
Now I would like to inject ClassA into Class1, .., Class4 implementations but ClassB into Class5. I'm aware that I can do that by injecting directly in implementing classes rather than in abstract class (as in Similar Question) but that means that I have to have the same field declared not once but five times. Additionally if I want to use this field in abstract class I would have to enforce creating getter in implementing class and use it to get that service. It works but it doesn't seem to me like right way to do it.
Here's one way to do it
#Component
class ClassA {}
#Component
class ClassB extends ClassA {}
abstract class AbstractClass {
protected ClassA classA;
}
#Component
class Class1 extends AbstractClass {
public Class1(ClassA classA) {
this.classA = classA;
}
}
//... Same for Class2/3/4
#Component
class Class5 extends AbstractClass {
public Class5(ClassB classB) {
this.classA = classB;
}
}
This lets you have the common property and methods in the abstract class and if qualify them in the child classes using constructor injection

Parametrize Bean factory by type in spring boot

I have a couple of interfaces which define some services:
public interface Service {
// marker
}
public interface ServiceA extends Service {
public method doA(AParameter a);
}
public interface ServiceB extends Service {
public method doB(BParameter b, AnotherParameter c);
}
Their implementations are always built the same way:
#Bean
public ServiceA getService() {
return new Servicebuilder().build(ServiceA.class);
}
#Bean
public ServiceB getService() {
return new Servicebuilder().build(ServiceB.class);
}
I use them with standard autowiring
class Controller {
private final ServiceA serviceA;
private final ServiceB serviceB;
#Autowired
public Controller(ServiceA service A, ServiceB serviceB) {
this.serviceA = serviceA;
this.serviceB = serviceB;
}
}
Now I want my team to be able to add new services simple by defining the interface without having to write the bean provider each time. So in principle, I want to do something like
#Bean
public <T extends Service> T getService(Class<T> clazz) {
return new Servicebuilder().build(clazz);
}
However, this fails with
Parameter 0 of constructor in Controller required a bean of type 'ServiceA' that could not be found.
I am using Spring Boot 1.5.1.
I have already looked at custom Qualifiers and there are lots of answers regarding generics in Beans. However none seems to fit my situation. Is there a way to achieve this?

Dynamically create Spring beans that extend an abstract class with parameterized types

I would like to take advantage of Spring 4.0's support for autowiring of generic types but I would like to avoid having to create explicit concrete or anonymous classes for each type. To use an example, lets say I have an interface:
public interface Cache<T extends Entity>
And an abstract implementation of the interface:
public abstract class AbstractCache<T extends Entity> implements Cache<T>
{
#Autowired
private EntityDao<T> dao;
#Autowired
private List<CacheListener<T>> listeners;
...
}
And entity classes A to Z that implement Entity (e.g):
public class A implements Entity
public class B implements Entity
...
public class Z implements Entity
Is there a way I can create instances of Cache<A> through Cache<Z> such that I can autowire these generic types in other classes? E.g.
#Autowire
private Cache<Z> zCache;
I know I can achieve this by individually defining each bean, E.g.
#Bean
public Cache<Z> cacheZ() {
return new AbstractCache<Z> () {};
}
But I have been unable to come up with a way to do this for all Entity classes in a particular package. E.g.
public void registerEntityCaches (BeanFactory beanFactory) {
for (Class<? extends Entity> cls : entityPackage.getAllClasses()) {
beanFactory.registerBean(new AbstractCache<cls>() {});
}
}
Is something like this possible or do I have to define them individually?

Categories