2

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);
    }
Brad
  • 15,186
  • 11
  • 60
  • 74
Steve
  • 4,457
  • 12
  • 48
  • 89
  • Possible duplicate of [How to call a method after bean initialization is complete?](http://stackoverflow.com/questions/1088550/how-to-call-a-method-after-bean-initialization-is-complete) – Jeremy Mar 04 '17 at 22:59

1 Answers1

3

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.

Mouad EL Fakir
  • 3,609
  • 2
  • 23
  • 37