1

我有一个具有 Authenticator 类的 Web 服务客户端。Authenticator 需要用户名/密码。寻求有关如何使用 Spring 注入凭据的帮助。

我应该将用户/密码注入到 Authenticator 中还是注入到正在实例化 Authenticator 的客户端中。

任何具体的例子都会受到赞赏,因为我是 Spring 新手。

这些是两个组件的样子:

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

身份验证器,带有凭据:

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());
    }
}
4

1 回答 1

1

用于@ValueAuthenticationbean中设置用户名/密码

@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());
    }
}

并在 XML 文件中

添加

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

并放入credentials.properties类路径

于 2012-07-02T13:15:34.053 回答