How to load different property value conditionally

327 views Asked by At

I have a condition where I want to use the same method to be called for request coming from mobile app and request coming from webapp with different clientId and different Client secret and redirect uris,base uris .

When a request comes from mob we have header "source" value as mobile and when request comes from web we have header "source" value as web.

I want to have something like that when request comes from web ,values of client id,clientsecret,baseurl,redirecturl of web is loaded and when request comes from mobile values of client id,clientsecret,baseurl,redirecturl of mobile is loaded.

I want to avoid to write the same logic either by creating in different method or different endpoint for mobile/web.I wan to use the same method and the same endpoint ,just that values injected from conifguration will be different based on the header value

How can I achieve this??Is there a way to @Autowire different config class based on condition

TokenController

public class TokenController {

@GetMapping("/getToken")
public ResponseEntity<?> fetchToken(@RequestParam("foo") String foo) {
    ResponseEntity<?> tokenInfo = tokenInfoServiceImpl.getTokenDetails(foo);
    return tokenInfo;

}}

TokenServiceImpl

public class TokenServiceImpl{

@Autowired
SSOConfig ssoConfig;

public ResponseEntity<?> getTokenDetails(String foo) {

    HttpHeaders tokenExchangeHeaders = prepareRestTemplateHeader(ssoConfig.getClientId(),
            ssoConfig.getClientSecret());
    String baseUrl =soConfig.getBaseurl();
    String redirectUrl = ssoConfig.getRedirectUrl();

         //rest of the logic        
}

}

SSOConfig class

@Configuration
@ConfigurationProperties(prefix = "sso.web")

public class SSOConfig {

private String baseurl;
private String redirectUrl;
private String tokenClientId;
private String tokenClientSecret;

//Getters and Setters

}
1

There are 1 answers

3
motopascyyy On

For your TokenController class, you should be able to add an argument to process a RequestHeader.

public class TokenController {

@GetMapping("/getToken")
public ResponseEntity<?> fetchToken(@RequestHeader(name = "source") String source, @RequestParam("foo") String foo) {
    ResponseEntity<?> tokenInfo = null;
    if ("mobile".equals(source)) {
        ResponseEntity<?> tokenInfo = tokenInfoServiceImpl.getTokenDetails(foo);
    } else {
    //do something else
    }
    return tokenInfo;

}}

There's a great tutorial on this at Baeldung