0

I've already gone through some tips on how to do this, like this one: stack overflow; but my problem is that my own implementation needs other things to be injected in it. Here's the example:

public interface MyService {}

public class ServiceImplA implements MyService {

     @Autowired
     private final SomeStuffA a_stuff;

}

public class ServiceImplB implements MyService {

     @Autowired
     private final SomeStuffB b_stuff;

}

@Configuration
public class SpringConfig {

    @Bean
    @Scope("singleton")
    public MyService getService() {
         boolean useA = // read config file and decide impl
         return useA ? new ServiceImplA() : new ServiceImplB();
         // I can't instantiate this, so i need them to be injected as well
    }

}

I'm familiar with Google Guice, where I would do something like this:

bind(MyServicle.class).to(useA ? ServiceImplA.class :  ServiceImplB.class);

So, I need a way to do this using Spring

shinjw
  • 3,329
  • 3
  • 21
  • 42

1 Answers1

2

I think your problem is that your base class MyService is not marked for any profile.

When you define profile the beans that have such specification will override beans that implement the same interface and do not have profile definition. This does not work this way.

When working with active profile X spring starts all beans that are not targeted for any profile and beans targeted for current profile. In your case you can choose wisely.

I think that if you want to use profiles you should define at least 2: A and B (the names are taken just for example.)

Now mark ServiceImplA as A and ServiceImplB as B:

@Service
@Profile("A") 
public ServiceImplA interface MyService { ... }
and some development implementation

@Service
@Profile("B") 
public ServiceImplB interface MyService { ... }

More about profiling you will get here

Sagar Gangwal
  • 7,544
  • 3
  • 24
  • 38