Reputation: 2983
I'm learning spring and in my first application I have different kind to bean (@Repository,@Service). Now I read that the default scope for these bean is singleton.
My situation is the following, I have two services where I'm injecting the same Dao.
@Service
public class MyFirtsServiceImpl implements MyFirtsService{
@Autowired
UserDao userDao
}
@Service
public class MySecondServiceImpl implements MySecondService{
@Autowired
UserDao userDao
}
@Repository
public class UserDao {
//methods to manage the persistence
}
Now I have some doubts about this situation. Being userDao a singleton bean then the instance to UserDao injected in both services is the same? How the container manage this?
Upvotes: 0
Views: 76
Reputation: 196
Isn't singleton scope the easiest case for the controller to manage?
It creates a bean for your:
@Repository
public class UserDao {
Also @Autowire is by type. So when it sees this:
@Autowired
UserDao userDao
it finds that there is only one bean it has created(or will create) of type UserDao, and there is no ambiguity in which one to inject. So it injects that bean here.
When it encounters the second identical @Autowire situation, it repeats the decision and so injects the same bean. It is not even an interesting decision.
Upvotes: 0
Reputation: 3005
first of all the meaning of singleton design pattern is only one instance per appliction and spring container manage singleton design pattern.
When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.
for more help go here
Upvotes: 1