Evaluating ${my.property} as a SpEL expression within a @Value annotation

南楼画角 提交于 2019-12-06 07:14:33

Maybe it just a matter of replacing @Factory with factory in the property value. This test passes for me:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpelTest.Config.class })
public class SpelTest
{
    @Value("#{${my.property}}")
    Product _product;

    @Test
    public void evaluating_spel_from_property_value() throws Exception
    {
        Assert.assertEquals(1234, _product.value);
    }

    @Component
    public static class Factory
    {
        public Product makeVal(int x) { return new Product(x); }
    }

    public static class Product
    {
        public final int value;

        public Product(final int value) { this.value = value; }
    }

    @Configuration
    @ComponentScan(basePackageClasses = SpelTest.class)
    public static class Config
    {
        @Bean
        public Factory factory() { return new Factory(); }

        @Bean
        public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
            final PropertySourcesPlaceholderConfigurer psc = new PropertySourcesPlaceholderConfigurer();
            final MutablePropertySources sources = new MutablePropertySources();
            sources.addFirst(new MockPropertySource()
                .withProperty("my.property", 
                          "factory.makeVal(1234)"));
            psc.setPropertySources(sources);
            return psc;
        }
    }
}    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!