복붙노트

[SPRING] 원격 PropertySource

SPRING

원격 PropertySource

누구나 속성 값을 검색 할 수있는 원격 소스 (예 : 데이터베이스)를 사용하는 PropertySource를 구축 한 사람이 있습니까? 아이디어는 PropertySource (host / port와 같은 연결 정보가 필요합니다)를 만들고 PropertySourcePlaceholderConfigurer에 연결하는 것입니다.

문제는 닭고기와 계란 문제 일 것 같습니다. 연결 정보를 PropertySource로 가져 오는 방법은 무엇입니까? 먼저 PropertySourcePlaceholderConfigurer를 인스턴스화하여 원격 호스트 및 포트 속성을 사용하여 속성 파일을로드 한 다음 나중에 PropertySource를 인스턴스화하고 다시 구성자로 주입 할 수 있습니다. 그러나 인스턴스화 될 초기 bean (및 구성 자로 신속하게 주입)이 제 특성 소스임을 보장 할 수있는 방법을 찾지 못하는 것 같습니다. 물론, 모든 다른 bean은 원격 특성에 의존하기 때문에 이것을 가지고 있어야합니다.

해결법

  1. ==============================

    1.Commons Configuration은 org.apache.commons.configuration.ConfigurationBuilder를 통해 다양한 소스 (JDBC 데이터 소스 포함)에서 org.apache.commons.configuration.Configuration 객체로 속성을로드하는 것을 지원합니다.

    Commons Configuration은 org.apache.commons.configuration.ConfigurationBuilder를 통해 다양한 소스 (JDBC 데이터 소스 포함)에서 org.apache.commons.configuration.Configuration 객체로 속성을로드하는 것을 지원합니다.

    org.apache.commons.configuration.ConfiguratorConverter를 사용하여 Configuration 객체를 PropertySourcesPlaceholderConfigurer에 전달할 수있는 java.util.Properties 객체로 변환 할 수 있습니다.

    ConfigurationBuilder를 구성하는 방법에 대한 닭고기와 계란 질문에 대해서는 org.springframework.core.env.Environment를 사용하여 시스템 속성, 명령 줄 속성 또는 JNDI 속성을 쿼리하는 것이 좋습니다.

    이 예에서 :

    @Configuration
    public class RemotePropertyConfig {
    
       @Bean
       public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer(Environment environment)
        throws Exception {
        final PropertySourcesPlaceholderConfigurer props = new PropertySourcesPlaceholderConfigurer();
        final ConfigurationBuilder configurationBuilder = new DefaultConfigurationBuilder(environment.getProperty("configuration.definition.file"));
        props.setProperties(ConfigurationConverter.getProperties(configurationBuilder.getConfiguration()));
        return props;
    }
    

    Commons Configuration을 구성하는 데 필요한 파일을 가리키는 환경 등록 정보 configuration.definition.file을 지정해야합니다.

  2. ==============================

    2.위의 Recardo의 대답과 유사하게 Apache의 대신에 Spring의 PropertiesLoaderUtils를 사용했지만 같은 결과가 나왔습니다. 정확히 이상적이지는 않습니다. 하드 코딩 된 의존성 삽입입니다.하지만 작동합니다!

    위의 Recardo의 대답과 유사하게 Apache의 대신에 Spring의 PropertiesLoaderUtils를 사용했지만 같은 결과가 나왔습니다. 정확히 이상적이지는 않습니다. 하드 코딩 된 의존성 삽입입니다.하지만 작동합니다!

    /**
     * This method must remain static as it's part of spring's initialization effort.
     * @return
     **/
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
      PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    
      String dbHost = null;
      Integer dbPort = null;
    
      // check system / environment properties first
      Environment environment = new StandardEnvironment();
      if (environment.containsProperty(DB_HOST_KEY)) {
        dbHost = environment.getProperty(DB_HOST_KEY);
      }
      if (environment.containsProperty(DB_PORT_KEY)) {
        dbPort = Integer.valueOf(environment.getProperty(DB_PORT_KEY));
      }
    
      if (dbHost == null || dbPort == null) {
        // ok one or (probably) both properties null, let's go find the database.properties file
        Properties dbProperties;
        try {
          dbProperties = PropertiesLoaderUtils.loadProperties(new EncodedResource(new ClassPathResource("database.properties"), "UTF-8"));
        }
        catch (IOException e) {
          throw new RuntimeException("Could not load database.properties.  Please confirm the file is in the classpath");
        }
    
        if (dbHost == null) {
          dbHost = dbProperties.getProperty(DB_HOST_KEY);
        }
        if (dbPort == null) {
          dbPort = Integer.valueOf(dbProperties.getProperty(DB_PORT_KEY));
        }
      }
    
      PropertySourceService propertySourceService = new DBPropertySourceService(dbHost, dbPort);
      PropertySource<PropertySourceService> propertySource = new DBPropertySource(propertySourceService);
      MutablePropertySources propertySources = new MutablePropertySources();
      propertySources.addFirst(propertySource);
      configurer.setPropertySources(propertySources);
    
      return configurer;
    }
    

    요청 당 원격 속성 소스의 소스가 여기에 있습니다. 그것은 할 수있는 '서비스'클래스에 달려 있습니다 .. 뭐든지 .. 소켓을 통한 속성의 원격 액세스, 데이터베이스와의 대화, 뭐든간에.

    /**
     * Property source for use with spring's PropertySourcesPlaceholderConfigurer where the source is a service
     * that connects to remote server for property values.
     **/
    public class RemotePropertySource extends PropertySource<PropertySourceService> {
    
      private final Environment environment;
      /**
       * Constructor...
       * @param name
       * @param source
       **/
      public RemotePropertySource(PropertySourceService source) {
        super("RemotePropertySource", source);
        environment = new StandardEnvironment();
      }
    
      /* (non-Javadoc)
       * @see org.springframework.core.env.PropertySource#getProperty(java.lang.String)
       */
      @Override
      public Object getProperty(String name) {
    
        // check system / environment properties first
        String value;
        if (environment.containsProperty(name)) {
          value = environment.getProperty(name);
        }
        else {
          value = source.getProperty(name);
        }
        return value;
      }
    }
    
  3. from https://stackoverflow.com/questions/25271537/remote-propertysource by cc-by-sa and MIT license