Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle two beans with the same name in Spring?

Tags:

java

spring

I have three jar and a war. A,B,C and D(war), A and B depend on C and D depends on A and B.
There's an interface X in C.
There is an implementation class Y for X in A and an implementation class Y for X in B, both of them have the same bean name in Spring.

Like this :

package com.example.a
class Y implements X

package com.example.b
class Y implements X

My Question:

In D, I want to use Spring to get both beans at the same time. How to do it?

In 'C':

package com.example.c
public interface X {
    String getPath();
}

In 'A':

package com.example.a
@Component
public class Y implements X {
    public String getPath(){
        return "/User/name/application";
    }
}

In 'B':

package com.example.b
@Component
public class Y implements X {
    public String getPath(){
        return "/usr/local/bin";
    }
}

In 'D':

package com.example.d
public class Application{
    @Autowired
    private List<? extends X> xes;
    public static void main(String[] args){
        for(X x : xes){
            System.out.println(x.getPath());
        }
    }
}

What do you do when A and B have exactly the same Y name ?

like image 446
Michael Avatar asked Oct 25 '25 11:10

Michael


1 Answers

Though both bean have the same type (interface) , you can give them two difference names:

@Bean
public X beanYInPackageA(){
   return new com.example.a.Y();
}

@Bean
public X beanYInPackageB(){
   return new com.example.b.Y();
}

And use @Qualifier to further define which beans to inject by its bean name (wire by name) on top of @Autowired :

@Autowired
@Qualifier("beanYInPackageA")
private X beanYInPackageA;

@Autowired
@Qualifier("beanYInPackageB")
private X beanYInPackageB;
like image 168
Ken Chan Avatar answered Oct 27 '25 02:10

Ken Chan