Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 393
user1298426 Avatar asked Oct 20 '25 16:10

user1298426


1 Answers

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

like image 120
user7294900 Avatar answered Oct 22 '25 06:10

user7294900



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!