How do I load one bean or another depending on the profile?

Viewed 106

I have two beans that implement the same interface. I have annotated one with:

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

@Service
@Profile("production")
public class MailServiceImpl implements MailService {

And the other one with:

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

@Service
@Profile("test")
public class SinkMailServiceImpl extends MailServiceImpl {

Then added the following configuration:

spring.profiles.active=test

Which successfully logs this when the application starts:

The following profiles are active: test

However I am getting this error:

Description:

Field mailService in fr.project.backend.service.impl.UserServiceImpl required a single bean, but 2 were found: - mailServiceImpl: defined in URL [jar:file:/app/app.jar!/BOOT-INF/classes!/fr/project/backend/service/impl/MailServiceImpl.class] - sinkMailServiceImpl: defined in URL [jar:file:/app/app.jar!/BOOT-INF/classes!/fr/project/backend/service/impl/SinkMailServiceImpl.class]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

I don't want to mark one as @Primary statically, and the @Qualifier annotation doesn't seem to fit my needs either. How do I load beans depending on the profile?

1 Answers

I think you can achieve this using the @ConditionalOnProperty(prefix= "spring.profiles", name = "active", havingValue = "test") annotation on your service classes where the property can be anything you like.

Related