2012-07-02 23 views
1

我有一個具有Authenticator類的Web服務客戶端。 Authenticator需要用戶名/密碼。尋找如何使用Spring注入憑據的幫助。連接一個本身具有構造函數的Bean

我應該將用戶/密碼注入到身份驗證器還是注入實例化身份驗證器的客戶端。

任何具體的例子,將不勝感激,因爲我是新的春天。

這些是兩個組件的樣子:

@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

使用@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在類路徑

相關問題