user1224036 user1224036 - 1 month ago 16
Java Question

Spring Lazy true or false based on a property

I want to define lazy true or false based on configuration properties,example below

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{
};

}


I cant define this in the context XML, the reason to externalize lazy option is simple bean is actually a cache, so i don't want to load the cache unless first request is made to it in some evironments

Answer

You can achieve this providing 2 configurations, and using those initialization based on property value:

@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{
    };

}