Java 管理单例bean
我正在学习spring,在我的第一个应用程序中,我有不同类型的bean(@Repository,@Service)。现在我了解到这些bean的默认作用域是singleton 我的情况如下,我有两个服务,其中我注入了相同的DaoJava 管理单例bean,java,spring,Java,Spring,我正在学习spring,在我的第一个应用程序中,我有不同类型的bean(@Repository,@Service)。现在我了解到这些bean的默认作用域是singleton 我的情况如下,我有两个服务,其中我注入了相同的Dao @Service public class MyFirtsServiceImpl implements MyFirtsService{ @Autowired UserDao userDao } @Service public class MySeco
@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
}
现在我对这种情况有些怀疑。如果userDao是单例bean,那么在两个服务中注入的userDao实例是相同的吗?容器如何管理这一点?首先,单例设计模式的含义是每个应用程序只有一个实例,而spring容器管理单例设计模式 当一个bean是一个单实例时,只管理该bean的一个共享实例,并且对具有与该bean定义匹配的一个或多个id的bean的所有请求将导致Spring容器返回该特定bean实例 换句话说,当您定义一个bean定义并将其范围限定为单例时,SpringIoC容器将恰好创建该bean定义所定义对象的一个实例。此单个实例将存储在此类单例bean的缓存中, 并且该命名bean的所有后续请求和引用都将导致返回缓存对象
要获得更多帮助,请转到singleton scope不是控制器最容易管理的情况吗 它为您的用户创建一个bean:
@Repository
public class UserDao {
此外,@Autowire是按类型排列的。因此,当它看到这一点时:
@Autowired
UserDao userDao
它发现它只创建了(或将创建)一个UserDao类型的bean,并且不存在注入哪个bean的歧义。所以它把豆子注射到这里
当它遇到第二个相同的@Autowire情况时,它会重复该决策,从而注入相同的bean。这甚至不是一个有趣的决定