Spring 在运行时选择 bean 实现 [英] Spring choose bean implementation at runtime

查看:36
本文介绍了Spring 在运行时选择 bean 实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用带有注解的 Spring Beans,我需要在运行时选择不同的实现.

I'm using Spring Beans with annotations and I need to choose different implementation at runtime.

@Service
public class MyService {
   public void test(){...}
}

例如对于windows平台我需要MyServiceWin扩展MyService,对于linux平台我需要MyServiceLnx扩展MyService.

For example for windows's platform I need MyServiceWin extending MyService, for linux platform I need MyServiceLnx extending MyService.

目前我只知道一个可怕的解决方案:

For now I know only one horrible solution:

@Service
public class MyService {

    private MyService impl;

   @PostInit
   public void init(){
        if(windows) impl=new MyServiceWin();
        else impl=new MyServiceLnx();
   }

   public void test(){
        impl.test();
   }
}

请注意,我仅使用注释而不使用 XML 配置.

Please consider that I'm using annotation only and not XML config.

推荐答案

可以将bean注入移动到配置中,如下:

You can move the bean injection into the configuration, as:

@Configuration
public class AppConfig {

    @Bean
    public MyService getMyService() {
        if(windows) return new MyServiceWin();
        else return new MyServiceLnx();
    }
}

或者,您可以使用配置文件 windowslinux,然后使用 @Profile 注释来注释您的服务实现,例如 @Profile("linux")@Profile("windows"),并为您的应用程序提供这些配置文件之一.

Alternatively, you may use profiles windows and linux, then annotate your service implementations with the @Profile annotation, like @Profile("linux") or @Profile("windows"), and provide one of this profiles for your application.

这篇关于Spring 在运行时选择 bean 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆