Search code examples
javaspringspring-annotations

Set common variable in Spring Configuration


I have a Java Spring Configuration class like this. I want to set a variable that several of my beans depend on, turn it into a bean, and use it as a dependency. How can I make the setVariable() method happen first? I'm converting my code from Guice, where this variable was being set in the overridden 'Configuration' method. Does Spring have something like that?

@Configuration
class SpringConfiguration{
    String variable;

    public void setVariable(){
        variable = System.getenv("whatever")
    }

    @Bean
public void variable(){
    return variable;
}

    @Bean
    public void myService(){
        return new MyService(variable);
    }

    @Bean
    public void myService2(){
        return new MyService2(variable);
    }

Solution

  • You can do something like this :

    @Configuration
    class SpringConfiguration {
    
        @Bean(name="variable")
        public String geVariable() {
            return System.getenv("whatever");
        }
    
        @Bean
        @DependsOn("variable")
        public MyService getMyService() {
            return new MyService(geVariable());
        }
    
        @Bean
        @DependsOn("variable")
        public MyService2 getMyService2() {
            return new MyService2(geVariable());
        }
    }
    

    Like that you can insure that variable will be initialized before service1 and service2, note that DependsOn in this case is just for clarification purposes.