我们在应用程序中使用单例服务类:
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,并开始在我们的 Controller 中使用 @Autowired 注释:
@RestController
@RequestMapping("/approvals")
public class ApprovalRestController extends BaseRestController {
@Autowired
transient private LevelApprovalService levelApprovalService;
}
问题是,由于这个原因,我们的 Web 应用程序当前每个单例服务都有 2 个实例:我们自己创建的单例和 Spring 创建的单例。 Autowiring 。我们不希望出现这种情况,并为所有内容使用一个单例实例。
有没有办法告诉 Spring 使用单例的 getInstance() 方法,同时仍然使用 Spring 注释将事物连接在一起?并非所有服务都在 Spring 前端中使用,因此我们需要让 Spring 使用我们的单例实例,而不是相反,而且我们不想切换到基于 xml 的配置或开始使用配置文件。
最佳答案
您可以在 @Configuration
类之一中定义 @Bean
方法。
@Configuration
public class Configuration {
@Bean
public LevelApprovalService getLevelApprovalService() {
return LevelApprovalServiceImpl.getInstance();
}
}
这样,Spring 将始终使用您创建的实例。
关于java - 使用现有的 Singleton 对象进行 Autowiring 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57413449/