Spring: Selecting @Service based on profile

shyam picture shyam · Jan 27, 2017 · Viewed 10.8k times · Source

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?

Answer

dunni picture dunni · Jan 27, 2017

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