2009-04-28 9 views
6

Java 스프링을 사용하여 런타임시 콩의 속성을 어떻게 동적으로 변경합니까? bean "mainView"가 있습니다.이 mainView는 "class1"또는 "class2"속성 "class"로 사용해야합니다. 이 결정은 "withSmartcard"속성이 "Y"또는 "N"인 속성 파일의 기반에서 이루어져야합니다.스프링 스프링을 동적으로 변경하십시오.

의 ApplicationContext :

<bean id="mainView" 
    class="mainView"> 
    <property name="angebotsClient" ref="angebotsClient" /> 
    <property name="class" ref="class1" /> 
</bean> 



<bean id="class1" 
    class="class1"> 
    <constructor-arg ref="mainView" /> 
</bean> 

<bean id="class2" 
    class="class2"> 
    <constructor-arg ref="mainView" /> 
</bean> 

PropertyFile :

withSmartcard = Y

답변

1

사용 클래스 팩터. 귀하의 재산에 따라 사례를 반환 할 수 있습니다.

10

귀하의 등록 정보 파일을 관리 할 수 ​​PropertyPlaceHolder를 사용 ..

<bean id="myPropertyPlaceHolder" 
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <description>The service properties file</description> 
    <property name="location" value="classpath:/some.where.MyApp.properties" /> 
    </bean> 

하고 다음과 같은 ref 속성 변경 : 당신의 속성에서

<bean id="mainView" 
    class="mainView"> 
    <property name="angebotsClient" ref="angebotsClient" /> 
    <property name="class" ref="${withSmartCardClassImplementation}" /> 
</bean> 

이 some.where.MyApp.properties 파일을하는 추가 키 withSmartCardClassImplementation이 값은 class1 또는 class2 (사용자가 선택 함)를 갖습니다.

withSmartCardClassImplementation=class1 
+0

{$ classIdToBeUsed} 또는 $ {classIdToBeUsed}가되어야합니까? –

+0

$ {classIdToBeUsed} :) Typo, 고마워요! 분명히, 나는 KSS 때문에 withSmartCardClassImplementation – Olivier

4

PropertyPlaceholderConfigurer을 원합니다. 설명서의 해당 부분은 내가 그 자리에서 할 수 있었던 것보다 더 잘 보여줍니다.

예를 들어, 속성 값을 class1 또는 class2 (봄 컨텍스트에서 원하는 bean의 이름)으로 변경해야합니다.

또는, 구성이 될 수있다 : 포함 된 구성 파일

<bean id="mainView" 
    class="mainView"> 
    <property name="angebotsClient" ref="angebotsClient" /> 
    <property name="class"> 
     <bean class="${classToUse}"> 
      <constructor-arg ref="mainView"/> 
     </bean> 
    </property> 
</bean> 

:되지 않을 것 콩 또는 클래스 이름을 사용 classToUse = fully.qualified.name.of.some.Class

사용자가 편집 할 수있는 구성 파일에서 사용할 수 있으며 실제로 구성 매개 변수 값으로 "Y"와 "N"을 사용해야합니다. 이 경우 Java에서이 작업을 수행하면됩니다. Spring은 turing-complete가 아닙니다.

if (this.withSmartCards) { 
    this.class_ = context.getBean("class1"); 
} else { 
    this.class_ = context.getBean("class2"); 
} 

청소기 솔루션은 자체 클래스에서 사용자 구성의 처리를 캡슐화 될 ApplicationContextAware해야 클래스의 수를 줄이기 위해 위를 할 것 : 직접 애플리케이션 컨텍스트에 액세스 할 수

MAINVIEW 필요에 따라 다른 클래스에 삽입하십시오.

BeanFactoryPostProcessor을 사용하면 프로그래밍 방식으로 클래스 속성의 정의를 등록 할 수 있습니다.FactoryBean을 사용하면 동적으로 빈을 생성 할 수 있습니다. 둘 다 Spring의 다소 고급 사용법입니다.

제쳐두고 : 나는 mainView와 class1/class2 사이의주기적인 의존성을 고려할 때 예제 구성이 합법인지 확실하지 않습니다.

1

@Olivier와 동의합니다.

여러 가지 방법이 있습니다.

  1. 사용 PropertyPlaceHolderConfigurer는 ..
  2. 사용 BeanPostProcessor ..
  3. 사용 스프링 AOP는 조언을 만들고 속성을 조작 할 수 있습니다.

위 항목 1을 권하고 싶습니다.

+0

그래, classIdToBeUsed 변경 : – Olivier

+0

예, 간단하고 쉽게 관리 할 .. – Satya

관련 문제