Is there a PropertyPlaceholderConfigurer-like class for use with Spring that accepts XML?

后端 未结 4 2094
轻奢々
轻奢々 2020-12-30 11:01

Spring has a very handy convenience class called PropertyPlaceholderConfigurer, which takes a standard .properties file and injects values from it into your bean.xml config.

4条回答
  •  再見小時候
    2020-12-30 11:50

    I just tested this, and it should just work.

    PropertiesPlaceholderConfigurer contains a setPropertiesPersister method, so you can use your own subclass of PropertiesPersister. The default PropertiesPersister already supports properties in XML format.

    Just to show you the fully working code:

    JUnit 4.4 test case:

    package org.nkl;
    
    import static org.junit.Assert.assertEquals;
    import static org.junit.Assert.assertNotNull;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    @ContextConfiguration(locations = { "classpath:/org/nkl/test-config.xml" })
    @RunWith(SpringJUnit4ClassRunner.class)
    public class PropertyTest {
    
        @Autowired
        private Bean bean;
    
        @Test
        public void testPropertyPlaceholderConfigurer() {
            assertNotNull(bean);
            assertEquals("fred", bean.getName());
        }
    }
    

    The spring config file test-config.xml

    
    
      
      
        
      
    
    

    The XML properties file properties.xml - see here for description of usage.

    
    
    
      fred
    
    

    And finally the bean:

    package org.nkl;
    
    public class Bean {
        private String name;
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
    }
    

    Hope this helps...

提交回复
热议问题