Spring choose bean implementation at runtime

后端 未结 5 1196
我寻月下人不归
我寻月下人不归 2020-11-29 21:23

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

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


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 21:28

    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();
        }
    }
    

    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.

提交回复
热议问题