EdgeCase
EdgeCase

Reputation: 4827

Wiring a Bean Which Itself has a Constructor

I have a web service client that has an Authenticator class. The Authenticator requires a username/password. Looking for help on how to inject the credentials using Spring.

Should I inject the user/pass into the Authenticator or into the client that is instantiating the Authenticator.

Any concrete examples would be appreciated, as I am new to Spring.

These are what the two components look like:

@Controller
    public class WSClient {
        @Autowired
        MyAuthenticator myAuthenticator;
    }
}

The Authenticator, with the credentials:

public class MyAuthenticator extends Authenticator {
    private final String userName;
    private final String passWord;

    public MyAuthenticator(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(this.userName, this.passWord.toCharArray());
    }
}

Upvotes: 1

Views: 72

Answers (1)

Jigar Joshi
Jigar Joshi

Reputation: 240898

Use @Value to set username/password in Authentication bean

@Component
public class MyAuthenticator extends Authenticator {
    @Value("${credentials.username}")
    private final String userName;
    @Value("${credentials.password}")
    private final String passWord;

    public MyAuthenticator(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(this.userName, this.passWord.toCharArray());
    }
}

and in XML file

add

<util:properties id="credentials" location="classpath:credentials.properties"/>

and put credentials.properties in classpath

Upvotes: 1

Related Questions