我想根据配置属性定义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实际上是一个缓存,所以我不想加载缓存,除非在某些环境中首先请求它
答案 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{
};
}