Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@autowired on method in Spring

I am learning Spring, and as far as I understand, when we use @annotation on a method which has a generic name (not a setter method), then the method's arguments are autowired.

public class MovieRecommender {

    private MovieCatalog movieCatalog;

    private CustomerPreferenceDao customerPreferenceDao;

    @Autowired
    public void prepare(MovieCatalog mC,
            CustomerPreferenceDao cPD) {
        this.movieCatalog = mC;
        this.customerPreferenceDao = cPD;
    }

    // ...

}

So, here, the fields movieCatalog and customerPreferenceDao are autowired with the values of mC and cPD. What I fail to understand is how is this different from the same method without the "@autowired".

I understand @autowired when applied to a Field name, but not able to understand when the values are explicitly being passed to the method (either a setter or any other method), then what does Spring do special?

like image 463
Nishit Avatar asked Sep 03 '15 17:09

Nishit


People also ask

Can we use @autowired on methods?

You can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file.

What does @autowired do in spring?

Starting with Spring 2.5, the framework introduced annotations-driven Dependency Injection. The main annotation of this feature is @Autowired. It allows Spring to resolve and inject collaborating beans into our bean.

Is @autowired mandatory in spring boot?

No. After Spring 4.3 If your class has only single constructor then there is no need to put @Autowired .

Is @autowired required on constructor?

Here the quote from the official documentation : As of Spring Framework 4.3, an @Autowired annotation on such a constructor is no longer necessary if the target bean only defines one constructor to begin with.


1 Answers

quite late answer, but here it is:

any method annotated with @Autowired is a config method. It is called on bean instantiation after field injection is done. The arguments of the method are injected into the method on calling.

like image 139
P.J.Meisch Avatar answered Oct 09 '22 18:10

P.J.Meisch