2017年12月20日 星期三

Java Spring - Mixing configurations

  • Importing & mixing configurations混搭
    • autowired會考慮所有container中的bean,不論是在JavaConfig、XML或是@CompnentScan
  • 在JavaConfig中引用XML config
    • 假設現在有兩個bean需要被宣告,其一是CompactDisc(BlankDisc 實作),另一個是CDPlayer,現將其定義於Java class且分開兩個config檔
    • @Configuration
      public class CDConfig {
        @Bean
        public CompactDisc compactDisc() {
          return new SgtPeppers();
        }
      }
      
    • 可以藉由@Import將另一個class組合再一起
    • @Configuration
      @Import(CDConfig.class)
      public class CDPlayerConfig {
        @Bean
        public CDPlayer cdPlayer(CompactDisc compactDisc) {
          return new CDPlayer(compactDisc);
        }
      }
      
    • 或是create high-level java config,在這個class中使用@Import將兩個java config class組合在一起
    • @Configuration
      @Import({CDPlayerConfig.class, CDConfig.class})
      public class SoundSystemConfig {
      }
      
    • 假設現在情境為,XML配置CompactDisc(BlankDisc 實作)
    • <bean id="compactDisc"
            class="soundsystem.BlankDisc"
            c:_0="Sgt. Pepper's Lonely Hearts Club Band"
            c:_1="The Beatles">
        <constructor-arg>
          <list>
            <value>Sgt. Pepper's Lonely Hearts Club Band</value>
            <value>With a Little Help from My Friends</value>
            <value>Lucy in the Sky with Diamonds</value>
            <value>Getting Better</value>
            <value>Fixing a Hole</value>
            <!-- ...other tracks omitted for brevity... -->
          </list>
         </constructor-arg>
      </bean>
      
    • 要讓Spring同時load XML(假設此為/config.xml)檔及其他Java config的配置,方法為@ImportResource,可以修改high-level的java config class
    • @Configuration
      @Import(CDPlayerConfig.class) // java config file
      @ImportResource("classpath:cd-config.xml") // XML file
      public class SoundSystemConfig {
      }
      
  • 在用XML config中引JavaConfig
    • 可以使用import element引用xml config file,有點像是@ImportResource注意<import> element只能夠其他的xml config file
    • <import resource="cd-config.xml" />
      <bean id="cdPlayer" class="soundsystem.CDPlayer" c:cd-ref="compactDisc" />
      
    • 可以使用<beam> element 載入java config file
    • <bean class="soundsystem.CDConfig" /> <--!可以將java config file組合再一起-->
      <bean id="cdPlayer" class="soundsystem.CDPlayer" c:cd-ref="compactDisc" />
      
    • 也可以建一個level更高的XML file
    • <bean class="soundsystem.CDConfig" /> <--! import java config file-->
      <import resource="cdplayer-config.xml" /><--!import xml config file-->
    • 不論是使用JavaConfig or XML config file,通常都會再創一個root configuration,如此可以將兩個或更多的config class或XML組合起來。另外也可以在這種root configuration啟用component-scan(<context:component-scan> 或 @ComponentScan)

沒有留言:

張貼留言