使用现有的单例对象进行自动装配注入

Using existing Singleton objects for Autowire injection

我们在应用程序中使用单例服务类:

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基于配置或开始使用配置文件。

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

@Configuration
public class Configuration {

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

}

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

您可以创建将单例实例添加到 spring 容器作为来自配置的 bean class:

@Configuration
public class MyConfig {

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

选择本机单例创建或 Spring 创建是正确的,顺便说一句,您的 getInstance() 不是线程安全的。