java - 使用现有的 Singleton 对象进行 Autowire 注入
问题描述
我们在应用程序中使用单例服务类:
public class LevelApprovalServiceImpl extends BaseBusinessServiceImpl implements LevelApprovalService {
/** There's one and only one instance of this class */
private static final LevelApprovalServiceImpl INSTANCE = new LevelApprovalServiceImpl();
/**
* Constructor is private, use getInstance to get
* an instance of this class
*/
private LevelApprovalServiceImpl() {
}
/**
* Returns the singleton instance of this class.
*
* @return the singleton instance of this class.
*/
public static LevelApprovalServiceImpl getInstance() {
return INSTANCE;
}
}
我们最近将 Spring 升级到 Spring 5,并开始在我们的控制器中使用 @Autowired 注解:
@RestController
@RequestMapping("/approvals")
public class ApprovalRestController extends BaseRestController {
@Autowired
transient private LevelApprovalService levelApprovalService;
}
问题在于,由于这个原因,我们的 Web 应用程序当前有每个单例服务的 2 个实例:我们自己创建的单例和 Spring 创建的单例。自动装配。我们宁愿不是这种情况,并且对所有事情都有一个单例实例。
有没有办法告诉 Spring 使用单例的 getInstance() 方法,同时仍然使用 Spring 注释将事物连接在一起?并非每个服务都在 Spring 前端中使用,因此我们需要让 Spring 使用我们的单例实例而不是相反,我们宁愿不必切换到基于 xml 的配置或开始使用配置文件。
解决方案
您可以在其中一个类中定义@Bean
方法@Configuration
。
@Configuration
public class Configuration {
@Bean
public LevelApprovalService getLevelApprovalService() {
return LevelApprovalServiceImpl.getInstance();
}
}
这样,Spring 将始终使用您创建的实例。
推荐阅读
- excel - 使用 Cells.Find 时出现运行时错误 91
- json - 使用 resttemplate Exchange 在 POST 请求正文中发送参数和列表
- java - 如何使用 JtextArea 添加滚动条并在 GUI 中实现 JScrollPane?
- php - 如何在 laravel 和 mysql 中选择和更新 10 个随机行
- c# - 从另一个线程更新 Datagrid 的 ItemSource
- curl - 使用 Curl 下载 HTML 进行解析的问题
- javascript - Google reCAPTCHA 在 .NET WebForms 中不起作用
- react-native - Expo 托管项目发布构建 apk 无法在模拟器或设备上启动
- c++ - Tesseract 不考虑其变量
- python - Visual Studio Code 的 Mac OS Mojave 麦克风权限