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).
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 thancom.myapp.test2.MyService
And if both are annotated with
@Service
and managed by Spring, you can inject them as follow :MyService 1 :
MyService 2 :
Injecting them :
That said, it would be easier to give different names to both classes.