1

I have an example that is something like this

The class Other needs an instance of MyBean so I'm creating an attribute and using that attribute while creating and Other

@Configuration 
public SomeClass {

     @Resource 
     private MyBean b;

     @Autowired
     Environment env;

     @Bean
     public MyBean myBean() {
         MyBean b = new MyBean();
         b.foo(env.getProperty("mb"); // NPE
         return b;
     }

     @Bean 
     public Other other() {
         Other o = new Other(o);
         return o;
     }
}

But I'm getting NullPointerException while initializing the myBean object, I guess that's because the env property has not been wired still at that point.

If I don't use the bean and use the method directly everything works well.

@Configuration 
public SomeClass {

     @Autowired
     Environment env;

     @Bean
     public MyBean myBean() {
         MyBean b = new MyBean();
         b.foo(env.getProperty("mb"); // NPE
         return b;
     }

     @Bean 
     public Other other() {
         Other o = new Other(myBean());
         return o;
     }
}

Is it because I'm defining the @Bean in the same @Configuration class?

OscarRyz
  • 196,001
  • 113
  • 385
  • 569

1 Answers1

1

Despite of it being interesting as a conceptual question, the way-to-go with the Spring Java configuration would be just to pass the required bean as a parameter, so you'd avoid autowiring beans as fields of a configuration class. If any of your beans happen to require the MyBean instance, just provide it as a parameter:

 @Bean 
 public Other other(MyBean myBean) {
     Other o = new Other(myBean);
     return o;
 }

There's no problem in calling @Bean anotated methods from your configuration classes too, as you're doing in your second code snippet, as they're proxied and cached, so they won't create unecessary instances. However, I tend to follow the code above as it allows the developer knowing the required dependencies in a quick glimpse.

Having said that, for your concrete question @Autowired works instead of @Resource, but it makes no sense to use any of them in a @Configuration class. Just use local method parameters.

Community
  • 1
  • 1
Aritz
  • 30,971
  • 16
  • 136
  • 217