首页 > 解决方案 > 使用现有的 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 的配置或开始使用配置文件。

标签: javaspringannotationssingleton

解决方案


您可以在其中一个类中定义@Bean方法@Configuration

@Configuration
public class Configuration {

    @Bean
    public LevelApprovalService getLevelApprovalService() {
        return LevelApprovalServiceImpl.getInstance();
    }

}

这样,Spring 将始终使用您创建的实例。


推荐阅读