Spring: Selecting @Service based on profile
Asked Answered
S

2

23

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?

Salgado answered 27/1, 2017 at 10:24 Comment(0)
L
18

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
Lareine answered 27/1, 2017 at 10:40 Comment(0)
Z
18

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.

Zoezoeller answered 26/4, 2018 at 13:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.