How to call different implementations of a bean based on profile in spring

user1298426 :

I need to add multiple implementations of an interface and one of them should be picked up based on profile.

For e.g.

interface Test{
    public void test();
}

@Service
@Profile("local")
class Service1 implements Test{
    public void test(){

    }
}

@Service
class Service2 implements Test{
    public void test(){

    }
}


@SpringBootApplication
public class Application {

    private final Test test;

    public Application(final Test test) {
        this.test = test;
    }

    @PostConstruct
    public void setup() {
        test.test();
    }
}

My intention is when I use -Dspring.profiles.active=local then Service1 should be called or else service2 should be called but I am getting an exception that the bean for Test is missing.

user7294900 :

Add default profile for Service2:

@Service
@Profile("default")
class Service2 implements Test{
    public void test(){

    }
}

the bean will only be added to the context if no other profile is identified. If you pass in a different profile, e.g. -Dspring.profiles.active="demo", this profile is ignored.

If you want for all profile except local use NOT operator:

@Profile("!local")

If a given profile is prefixed with the NOT operator (!), the annotated component will be registered if the profile is not active

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143566&siteId=1