连接一个自己有构造函数的Bean

时间:2012-07-02 13:12:46

标签: java spring

我有一个具有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());
    }
}

1 个答案:

答案 0 :(得分:1)

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

并在XML文件中

添加

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

并将credentials.properties放在classpath