I have an interface define as below:
public interface MyService { }
And two classes implementing it:
@Service @Profile("dev") public class DevImplementation implements MyService { }
and
@Service @Profile("prod") public class ProdImplementation implements MyService { }
And there's another service trying to use it:
@Service public MyClass { @Autowired MyService myservice; }
The problem is that I'm getting NoSuchBeanException
when running the code. It's run using
mvn spring-boot:run -P dev
What am I doing wrong?
Use @Profile on a Bean Let's start simple and look at how we can make a bean belong to a particular profile. We use the @Profile annotation — we are mapping the bean to that particular profile; the annotation simply takes the names of one (or multiple) profiles.
The solution would be to create more property files and add the "profile" name as the suffix and configure Spring Boot to pick the appropriate properties based on the profile. Then, we need to create three application. properties : application-dev.
Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.
Another way to do this is to have a production profile and the development is implicit on it not being set e.g.
@Component @Profile("prod") public class ProdImplementation implements MyService { }
... and the developer implementation has a profile of "!prod".
@Component @Profile("!prod") public class DevImplementation implements MyService { }
So to run in production mode you must type the profile ...
> mvn spring-boot:run -Dspring.profiles.active=prod
... and development mode doesn't require a profile ...
> mvn spring-boot:run
IMO a bit easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With