사용자 도구

사이트 도구


springframework:propertysource

문서의 이전 판입니다!


PropertySource

프라퍼티 추가

코딩을 통한 임의의 프라퍼티 소스 추가

일반 Java 애플리케이션

ConfigurableApplicationContext ctx = new GenericApplicationContext();
MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
sources.addFirst(new MyPropertySource());

웹 애플리케이션

  • web.xml
    <context-param>
        <param-name>contextInitializerClasses</param-name>
        <param-value>com.bank.MyInitializer</param-value>
    </context-param>
  • TestContext에서 web.xml없이 Java Code로 등록하기
    @ContextConfiguration(initializers = MyInitializer.class)
  • MyInitializer.java
    public class MyInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
        public void initialize(ConfigurableWebApplicationContext ctx) {
            PropertySource ps = new MyPropertySource();
            ctx.getEnvironment().getPropertySources().addFirst(ps);
            // perform any other initialization of the context ...
        }
    }

ApplicationContextInitializer를 Java 코드 기반 ApplicationContext에서 사용하기

  • java - ApplicationContextInitializer in a non-web Spring Context?
    // Create context, but dont initialize with configuration by calling 
    // the empty constructor. Instead, initialize it with the Context Initializer.
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    MyAppContextInitializer initializer = new MyAppContextInitializer();
     
    // ApplicationContextInitializer가 ApplicationContext를 초기화해주는 형태
    initializer.initialize( ctx );
     
    // @Configuration 클래스를 등록하고 초기화
    ctx.register( com.my.classpath.StackOverflowConfiguration.class );
    ctx.refresh()

@Configuration 클래스에서 XML 프라퍼티를 프라퍼티 소스로 등록하기 예제

3.2 최신 버전에서는 이 기법을 사용할 필요가 없다. ApplicationContextInitializer를 사용하자. 현재(3.1.2) @PropertySource를 통해서는 XML 프라퍼티를 등록할 수 없는 상태인데, @Configuration Java 클래스에서 직접 등록할 수 있다. ConfigurableApplicationContext를 주입 받은 것에 주의하라. ApplicationContext로 주입 받으면 안 된다. 프라퍼티 소스의 이름도 겹치면 안 된다.

@Configuration
public class SpringConfig {
 
  @Autowired
  private org.springframework.context.ConfigurableApplicationContext applicationContext;
 
  @Autowired
  private org.springframework.core.io.ResourceLoader resourceLoader;
 
  @PostConstruct
  public void addXmlProperties() throws Exception {
    addXmlProperties("classpath:my-properties.xml");
    addXmlProperties("classpath:my-properties2.xml");
  }
 
  private void addXmlProperties(String location) throws IOException,
      InvalidPropertiesFormatException {
    Resource resource = resourceLoader.getResource(location);
 
    Properties properties = new Properties();
    properties.loadFromXML(resource.getInputStream());
    applicationContext
        .getEnvironment()
        .getPropertySources()
        .addLast(
            new PropertiesPropertySource(
                getNameForResource(resource), properties));
  }
 
  // from ResourcePropertySource
  private static String getNameForResource(Resource resource) {
    String name = resource.getDescription();
    if (!StringUtils.hasText(name)) {
      name = resource.getClass().getSimpleName() + "@"
          + System.identityHashCode(resource);
    }
    return name;
  }
 
  @Bean
  public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
  }
}

PlaceHolder로 사용하기

PropertySource에 등록된 프라퍼티들을 @Value(“${property.name}”) 형태로 사용하려면 PropertySourcesPlaceholderConfigurer 등록이 필요하다.

  • Java 코드 설정시
    @Configuration
    @PropertySource("my.properties")
    public class SpringConfig {
      @Bean
      public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
      }
    }
  • XML로 설정시
      <context:property-placeholder location="classpath:my-properties.xml"/>
      <!--
          <context:property-placeholder/>는 Spring 3.1에서는 PropertySourcePlaceholderConfigurer 로 초기화된다.
          이 때 location에 지정된 프라퍼티도 place-holder로 적용하게 된다.
          현재(Spring 3.1.2)에는 XML Property를 못 추가하는 버그가 있는데 이를 통해 우회 가능하다.
          단, 이렇게 location에 들어간 프라퍼티는 공식 Environment의 PropertySource로 추가되지는 않는다.
          따라서 org.springframework.core.env.Environment.getProperty()로는 읽을 수 없다.
          가능하면 위에 설명한 @Configuration Java 클래스에서 프라퍼티 소스 등록하기 예제를 사용하는게 낫다.
          @ 확인 필요 : 이 경우 자식 ApplicationContext에서도 location에 지정된 프라퍼티는 place-holder로 사용할 수 없을 것이다. @
      -->
springframework/propertysource.1443712029.txt.gz · 마지막으로 수정됨: 2015/10/01 23:37 저자 kwon37xi