如何使用@Configuration定义配置运行时?

时间:2015-05-28 22:06:46

标签: java spring

我是春天的新手,所以请耐心等待,如果你认为有必要,可以随意建议使用正确的链接。我正在使用一个类来定义我将要呼叫的不同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。帮助赞赏!

2 个答案:

答案 0 :(得分:2)

更好的方法是使用工厂设计模式。有点像:

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

答案 1 :(得分:0)

要做的两件事:

  1. RestServer移到外部,它不应该是RestConfiguration的内部类。
  2. 使用scope=DefaultScopes.PROTOTYPE以允许创建多个RestServer个实例,每个注入点一个:

      @Bean(scope=DefaultScopes.PROTOTYPE)
      public RESTServer restServer(Environment env) { ...