【问题标题】:How do I provide runtime specific configuration metadata to Spring?如何向 Spring 提供运行时特定的配置元数据?
【发布时间】:2011-10-28 12:48:22
【问题描述】:

我正在编写一个客户端/服务器应用程序并使用 Spring 对其进行配置。

我的客户端界面处理对服务器的编组请求并处理响应。

目前,我有一个看起来像这样的工厂:

public class ClientFactory {
    private ApplicationContext ctx;
  public ClientFactory(){
    ctx = new AnnotationConfigApplicationContext(MyConfig.class);
  }

  public MyClient(String host, int port){
    MyClient client = ...
    // create a connection to the server
    return client;
  }
}

现在,MyClient 有一堆我想注入的依赖项,所以我想使用 Spring 创建 MyClient 实例并使用 @Inject 注解来注入依赖项。

如何将主机/端口作为配置元数据传递到 Spring 配置中?如果我不能,推荐的替代方案是什么。我可以自己完成所有的接线,但这就是 Spring 的用途。

杰夫

【问题讨论】:

    标签: java spring dependency-injection factory


    【解决方案1】:

    您应该检查弹簧参考的配置部分。例如,您可以使用 spring 3.x 创建这样的 bean。

    @Configuration
    // spring config that loads the properties file
    @ImportResource("classpath:/properties-config.xml")
    public class AppConfig {
    
        /**
         * Using property 'EL' syntax to load values from the
         * jetProperties value
         */
        private @Value("#{jetProperties['jetBean.name']}") String name;
        private @Value("#{jetProperties['jetBean.price']}") Long price;
        private @Value("#{jetProperties['jetBean.url']}") URL url;
    
        /**
         * Create a jetBean within the Spring Application Context
         * @return a bean
         */
        public @Bean(name = "jetBean")
        JetBean jetBean() {
            JetBean bean = new JetBeanImpl();
            bean.setName(name);
            bean.setPrice(price);
            bean.setUrl(url);
            return bean;
        }
    
    }
    

    【讨论】:

    • 是的,但这仍然需要一个包含所需 jetProperties 定义的预定义属性文件。我希望在运行时指定这些。也许我可以考虑动态创建这些属性。
    • Beans 是在运行时创建的。这意味着可以使用自定义运行时逻辑设置这些 setName、setPrice 方法。您不必使用预定义的属性。
    【解决方案2】:

    我使用静态配置类解决了这个问题。

    public class ClientFactory {
        private ApplicationContext ctx;
      public ClientFactory(){
        ctx = new AnnotationConfigApplicationContext(MyConfig.class,ServerConfig.class);
      }
    
      public MyClient(String host, int port){
        MyClient client = ...
        // create a connection to the server
        return client;
      }
    
      @Data
      @AllArgsConstructor
      public static class ServerDetails{
         private int port;
         private String host;
      }
    
      @Configuration
      public static class ServerConfig{
         static String host;
         static int port;
    
         @Bean
         public void serverDetails(){
            return new ServerDetails(host, port);
         }
      }
    }
    

    虽然感觉很笨重。有没有更好的办法?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 2012-03-09
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多