Spring Lazy基于属性的true或false

时间:2016-11-02 11:25:47

标签: java spring

我想根据配置属性定义lazy true或false,例如

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.PropertySource;


@Configuration
@PropertySource({"classpath:simple.properties"})
public class SimpleConfiguration {

    @Value("${simplebean.lazy.init}")
    private boolean lazyInit;

    @Bean
    @Lazy() //How to add the lazyInit config here?
    public SimpleBean getSimpleBean(){
       return  new SimpleBean();
    }

    public static class SimpleBean{
    };

}

我无法在上下文XML中定义它,外化lazy选项的原因是简单bean实际上是一个缓存,所以我不想加载缓存,除非在某些环境中首先请求它

1 个答案:

答案 0 :(得分:1)

您可以实现此目的,提供2种配置,并使用基于属性值的初始化:

@Configuration
@ConditionalOnProperty(value = "simplebean.lazy.init", havingValue="true") 
@PropertySource({"classpath:simple.properties"})
public class LazySimpleConfiguration {


    @Bean
    @Lazy(true) 
    public SimpleBean getSimpleBean(){
       return  new SimpleBean();
    }

    public static class SimpleBean{
    };

}


@Configuration
@ConditionalOnProperty(value="simplebean.lazy.init", havingValue="false")
@PropertySource({"classpath:simple.properties"})
public class SimpleConfiguration {


    @Bean
    @Lazy(false)
    public SimpleBean getSimpleBean(){
       return  new SimpleBean();
    }

    public static class SimpleBean{
    };

}