Issue
In a class with the @Configuration
annotation, that has a method with the @Bean
annotation, is it necessary to have an @Autowired
field of the same name as the bean in order to use it within this same class? Since the configuration class created the bean, should it not have immediate access to it by calling the method directly?
Eg:
@Configuration
public class ConfigClass
{
@Autowired
private BeanForSomething beanForSomething;
@Bean
public BeanForSomething beanForSomething()
{
return new BeanForSomething();
}
private void methodThatUsesBean()
{
beanForSomething.doSomething();
}
}
Is it not possible to leave out the @Autowired
field and just call beanForSomething().doSomething();
to use the bean? Perhaps I'm misunderstanding the usage of the @Bean
annotation.
Solution
No, the @Bean
declaration already takes care of that. You just need to call beanForSomething()
in methodThatUsesBean()
Answered By - rorschach
Answer Checked By - Candace Johnson (JavaFixing Volunteer)