1
votes

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?

2

2 Answers

1
votes

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

0
votes

Using Annotations that solutions

public class MyClass implements IMyClass{

    private OtherClassInjection otherClassInjection;

    private OtherClassInjection2 otherClassInjection2;

    MyClass(OtherClassInjection otherClassInjection, OtherClassInjection2 otherClassInjection2){
        this.otherClassInjection=otherClassInjection;
        this.otherClassInjection2=otherClassInjection2;
    }

    public void useObject(){
        otherClassInjection.user();
    }

}

@Bean(name = "myClass")
@Autowired
@Scope("prototype") //Define scope as needed
public MyClass getMyClass(@Qualifier("otherClassInjection") OtherClassInjection otherClassInjection, 
                          OtherClassInjection2 otherClassInjection2) throws Exception
{
    return new MyClass(otherClassInjection, otherClassInjection2);
}

that logical, it's work injection @Autowired when create a Bean if context are know that bean, that you will to want inject.

I'm use that way.