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.
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.
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.
Annotate your @Component
class with @Profile("profilename")
so the component will be injected based on the profile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With