我試圖找到一種方法,我可以在配置文件中指定一個類,以及應該傳遞給構造函數的參數。Java配置文件實例化具有參數的對象
例如,假設下面的XML配置文件:
<AuthServer>
<Authenticator type="com.mydomain.server.auth.DefaultAuthenticator">
<Param type="com.mydomain.database.Database" />
</Authenticator>
</AuthServer>
現在,在我的Java代碼,我要做到以下幾點:
public class AuthServer {
protected IAuthenticator authenticator;
public AuthServer(IAuthenticator authenticator) {
this.authenticator = authenticator;
}
public int authenticate(String username, String password) {
return authenticator.authenticator(username, password);
}
public static void main(String[] args) throws Exception {
//Read XML configuration here.
AuthServer authServer = new AuthServer(
new DefaultAuthenticator(new Database()) //Want to replace this line with what comes from the configuration file.
);
}
}
我可以讀課程的XML,並從中獲取值,但是我不確定如何模擬上面指出的行(想要替換...)以及來自XML配置文件的值的註釋。有沒有辦法做這樣的事情?
你可以考慮[spring framework](http://static.springsource.org/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-instantiation)。 – pd40 2013-02-20 02:13:36