Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Selecting @Service based on profile

Tags:

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?

like image 939
shyam Avatar asked Jan 27 '17 10:01

shyam


People also ask

How do you define beans for a specific profile?

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.

How do I manage profiles in Spring boot?

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.

How do I set environment specific properties in Spring boot?

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.


Video Answer


1 Answers

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.

like image 74
bobmarksie Avatar answered Sep 23 '22 08:09

bobmarksie