shyam
shyam

Reputation: 6771

Spring: Selecting @Service based on profile

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?

Upvotes: 24

Views: 21231

Answers (2)

bobmarksie
bobmarksie

Reputation: 3626

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.

Upvotes: 19

dunni
dunni

Reputation: 44515

With -P you enable a Maven profile. However Maven profiles are independent of Spring profiles. As long as you don't have the Maven profile configured to set the appropriate Spring property, you have to enable the Spring profile this way:

mvn spring-boot:run -Dspring.profiles.active=dev

Upvotes: 18

Related Questions