Is it possible to define to bean with same name in two different namespace without using @Qualifer and @resource

1.8k views Asked by At

I have two packages and beans as below in spring

com.myapp.test1

  • myService

com.myapp.test2

  • myService

part 1:The solution for this situation is giving name for beans like this:

@Service(name="myService1")
myService

and

 @Service(name="myService2")
 myService

and Inject like

@Autowire
@Qualifier("myService1")

Is there any solution without part1 approach, I required define two bean with same name in different namespace without name & @Qualifier

for theme (I am using spring).

1

There are 1 answers

4
Matt On

By default, Spring will give a name to the bean based on AnnotationBeanNameGenerator. So for same class name (even though on different packages), they will be givem the same name and fail.

As you tried the simplest solution is to give a name to one (or both) of the beans in your @Service annotation.

But then, you won't have to specify this name when injecting it as injection is looking for class instance, and in this case both classes are different.

com.myapp.test1.MyService is a different class than com.myapp.test2.MyService

And if both are annotated with @Service and managed by Spring, you can inject them as follow :

MyService 1 :

package com.myapp.test1;

@Service
public class MyService {

}

MyService 2 :

package com.myapp.test2;

@Service("myService2")
public class MyService {

}

Injecting them :

@Controller
public class MyController {
    @Autowired
    //no need for qualifier here
    private com.myapp.test1.MyService myService1;
    @Autowired
    //no need for qualifier here
    private com.myapp.test2.MyService myService2;
    ...
}

That said, it would be easier to give different names to both classes.