Shakthi
Shakthi

Reputation: 864

Constructor Injection using Parameter

I have the following bean with parameterized constructor:

@Component
public class AuthHelper{
    @Autowired
    private AuthClient gmailClient;
    @Autowired
    private AuthClient yahooClient;

    private AuthClient client;

    public AuthHelper client(String option) {
        if(option.equals("gmail")) this.client=gmailClient;
        if(option.equals("yahoo")) this.client=yahooClient;
        return this;
    }

    public boolean authLogic(String uid, String pass) {
        return client.authorize(uid,pass);
    }

}

Could you please help to autowire the above bean:

I am stuck while I call the above bean in the below service,

@Service
public class AuthService{
    @Autowired
    public AuthHelper authHelper;

    public boolean authenticate(String uid, String pass){
        return authHelper.client("gmail").authLogic(uid, pass);
    }

}

Please suggest... I want the helper class should use the bean based on the parameter that I pass from the service.

After Modification: The above example is working fine. Please suggest if there is any issue in this implementation...

Upvotes: 1

Views: 858

Answers (1)

Sup19
Sup19

Reputation: 102

IMO, the better approach would be to have a AuthHelperFactory which should provide the AuthHelper bean with appropriate client as per input.

public class AuthHelper{

private AuthClient client;

public AuthHelper (AuthClient client) {
    this.client = client;
}

public boolean authLogic(String uid, String pass) {
    return this.client.authorize(uid,pass);
}

}

@Component
public class AuthHelperFactory {
  @Autowired
  private AuthClient gmailClient;
  @Autowired
  private AuthClient yahooClient;

  public AuthHelper getAuthHelper(String option) {
     if(option.equals("gmail")){
        return new AuthHelper(gmailClient);
     } else if (option.equals("yahoo")){
        return new AuthHelper(yahooClient); 
     }
  }
 }

In the AuthService, you need to call the factory method in authenticate method.

return authHelperFactory.getAuthHelper("gmail").authLogic(uid, pass);

Upvotes: 2

Related Questions