[英]How to use @Configuration to define configurations runtime?
我對春季還很陌生,所以請耐心等待,如有需要請隨意提出更多建議,並提供正確的鏈接。我正在使用一個類來定義我將要調用的其他Rest終結點的連接設置(用戶名端口等)。 所以我正在考慮將它們存儲到application.properties中,如下所示:
twitter.username="a"
twitter.password="b"
twitter.host="www.twitter.com"
facebook.username="c"
facebok.password="d"
facebook.host="www.facebook.com"
現在,我想定義一個將使用所有前綴的類(例如“ twitter”或“ facebook”),並根據applicaton.properties中的相應屬性向我返回配置類。
我正在考慮做類似以下的事情:
@Configuration
@PropertySource("classpath:application.properties")
public class RESTConfiguration
{
class RESTServer{
public String username;
public String password;
public String host;
private RESTServer(String username, String password, String host)
{
this.username = username;
this.password = password;
this.host = host;
}
}
@Autowied
private String ednpointName;
@Bean
public RESTServer restServer(Environment env)
{
return new RESTServer(env.getProperty(ednpointName + ".user"),
env.getProperty(ednpointName + ".password"),
env.getProperty(ednpointName+".host"));
}
}
但這顯然不起作用,因為只有一個Bean,而且我也沒有辦法傳遞多個endpointName。 幫助贊賞!
更好的方法是使用工廠設計模式。 類似於以下內容:
@Configuration
@PropertySource("classpath:application.properties")
public class RESTConfiguration
{
@Bean
public RESTServerFactory restServer()
{
return new RESTServerFactory()
}
}
public class RESTServer {
public String username;
public String password;
public String host;
private RESTServer(String username, String password, String host)
{
this.username = username;
this.password = password;
this.host = host;
}
}
public class RESTServerFactory {
@Autowired Environment env;
public RESTServer getRESTServer(String endpointName)
{
return new RESTServer(env.getProperty(ednpointName + ".username"),
env.getProperty(ednpointName + ".password"),
env.getProperty(ednpointName+".host"));
}
}
使用此工廠的示例:
@Autowired RESTServerFactory factory;
public RESTServer createServer(String endpoint) {
return factory.getRESTServer(endpoint);
}
有兩件事要做:
RestServer
移到其自己的類之外,而不應該是RestConfiguration
的內部類。 使用scope=DefaultScopes.PROTOTYPE
以便創建多個RestServer
實例,每個注入點一個:
@Bean(scope=DefaultScopes.PROTOTYPE) public RESTServer restServer(Environment env) { ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.