Issue
I have a class that is annotated @Component
that was then @Autowired
into another class. However, I need to remove this @Component
annotation and instead, create it with an @Bean
annotated method in the class where its was previously autowired.
Where previously the classes looked like:
@Component
public class MyClass implements IMyClass
{
// Stuff
}
@Configuration
public class MyUsingClass
{
@Autowired
private IMyClass myClass;
private void methodUsingMyClass()
{
myClass.doStuff();
}
}
So now I have removed the @Component
annotation and written a @Bean
annotated method like this:
public class MyClass implements IMyClass
{
// Stuff
}
@Configuration
public class MyUsingClass
{
@Bean
public IMyClass getMyClass()
{
return new MyClass();
}
....
}
My question is around replacing the previous call of myClass.doStuff()
to use the new bean. Do I now pass in a parameter of type MyClass
to the private method:
private void methodUsingMyClass(final MyClass myClass)
{
myClass.doStuff();
}
... or do I call this method directly (doesn't seem the correct way to me):
private void methodUsingMyClass()
{
getMyClass().doStuff();
}
... or are neither of these correct?
Solution
I think you misunderstand the @Bean
annotation. It can be used to create a Bean. So basically spring will scan all classes, will find your @Bean
and create a Bean, not more. You can now use this bean, like if you would use one created with <bean></bean>
. To actually use the bean you need to either get it from ApplicationContext
or @Autowire
it. Of course you can still use that function like any other function in your code, to create a new instance of that object, but that would contradict to what you want to achieve with beans
Answered By - JohnnyAW
Answer Checked By - Marilyn (JavaFixing Volunteer)