iranichai
iranichai

Reputation: 383

Switching between profiles to manage multiple implementations on one spring interface

I am trying to use different implementations of a Spring Interface with different profiles. I have multiple modules that have code in different modules. Interface and 2 implementations are in a module and the class that calls the Interface is in a different module. My code is something like this:

from module1:

public class FirstService {

    @Autowired
    private Interface interfaceImplementation;
}

from module2:

public interface Interface {

}
@Service
@Profile("develop")
public class InterfaceImpl1 implements Interface {

}
@Service
@Profile("test")
public class InterfaceImpl2 implements Interface {

}

when I start my application, the application failed to start with the following error:

Field interface in FirstService required a bean of type Interface that could not be found

Thanks for the help.

Upvotes: 1

Views: 681

Answers (2)

iranichai
iranichai

Reputation: 383

I was able to fix this issue by adding the base package of the interface, implementations that are in a separate module to the @ComponentScan in the application.

Upvotes: 1

S Manikandan
S Manikandan

Reputation: 148

While on you application is started up on your default profile so there will be no bean of type "Interface" because in your code Implementation of "Interace" will be created by spring only if your app is started in "develop" or "test" profile. there are number of ways to set the profile in spring and easiest way set it as System parameter or environmental variable

Eg of setting as System parameter

-Dspring.profiles.active=develop or -Dspring.profiles.active=test (according which environment you are running)

Eg of setting as environmental variable

linux:- export spring_profiles_active=true windows:- set spring_profiles_active=true

Upvotes: 0

Related Questions