Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject dependency dynamically based on profile in spring boot

Let's say I have below setup, one interface I have has one method addTaxTrans():

public interface TaxTransInterface {

    Response<Map<String, Object>> addTaxTrans(Long sessionId, TaxMap taxMap);

}

I have two classes implemented with this interface.

First impementation for client1

@Component
public class Client1TaxImpl implements TaxTransInterface {

    @Override
    public Response<Map<String, Object>> addTaxTrans(Long sessionId, TaxMap taxMap) {
        // Common code + client 1 customization code
    }
}

Second implementation for client 2

@Component
public class Client2TaxImpl implements TaxTransInterface {

    @Override
    public Response<Map<String, Object>> addTaxTrans(Long sessionId, TaxMap taxMap) {

        // Common code + Client 2 customization code
    }
}

Below is the service implementation, here I have autowired TaxTransInterface and calling addTaxtrans method:

@Service
public class TaxSerImpl implements TaxSer {

    @Autowired
    private TaxTransInterface taxTransInterface;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response<Map<String, Object>> addTax(TaxReq taxReq) {

        // Calling Trans Function
        return taxTransInterface.addTaxTrans(taxReq.getSessionId(), 
                        taxReq.getTaxMap());
    }
}

As of now I am not able to run the project getting below error:

Field taxTransInterface required a single bean, but 2 were found:

I know this error comes because two implementations I have for interface TaxTransInterface

So do we have any option like dynamically when I run application by below command for profile client1:

java -jar -Dspring.profiles.active=client1 sbill-0.0.1-SNAPSHOT.war

then dynamically Client1TaxImpl should get inject and when run application for client2 then Client2TaxImpl should get injected.

Any suggestions?

Thanks in advance.

like image 743
user1731485 Avatar asked Sep 02 '19 09:09

user1731485


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 set active profile in Spring boot programmatically?

You can programmatically set active profiles by calling SpringApplication. setAdditionalProfiles(...) before your application runs. It is also possible to activate profiles using Spring's ConfigurableEnvironment interface.


1 Answers

Annotate your @Component class with @Profile("profilename") so the component will be injected based on the profile.

like image 181
Karthikeyan Vaithilingam Avatar answered Nov 14 '22 21:11

Karthikeyan Vaithilingam