2

In the Spring reference guide it says that you can apply @Autowired annotation to methods with arbitrary names and/or multiple arguments as shown in the following code.

public class MovieRecommender {

    private MovieCatalog movieCatalog;

    private CustomerPreferenceDao customerPreferenceDao;

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

    // ...

}

But the prepare() method is not going to be called by the Spring container because its not a setter method. How does @Autowired work in this situation?

1
  • Why is this not a setter method? Commented Jan 16, 2015 at 22:13

3 Answers 3

3

It does not say you can use @Autowired for any method what it says is

Config methods may have an arbitrary name and any number of arguments; each of those arguments will be autowired with a matching bean in the Spring container.

<beans>
<bean id="myBean" class="..." init-method="prepare"/>
</beans>
0
3

The annotation @Autowired does not really care which method name you use. So, a method name like prepare works just as well as a method name along the lines of setMovieCatalog.

Furthermore, Spring handles multiple arguments in the method with @Autowired as well. This is typically used for constructor based injection but works out just fine for other methods (like your prepare-method).

So, what is required to make this work? Well, first of all the arguments to the method must be beans that are known by the Spring context. This means that the beans must be wired in the XML-context, annotated with a @Component, or a @Bean from a @Configuration class. Secondly, the class that holds the @Autowired method must also be a bean that is known to the Spring context.

If both of the above are fulfilled, the @Autowired simply works as expected. It can be used on any instance method no matter the name.

0
1

No matter whats the method name, @Autowired will try get auto wire during spring context initialization.

2
  • So any method that is annotated with @Autowired will be called by the container during the initialization, right? It doesn't need to be a setter method or constructor method. Commented Jan 17, 2015 at 0:57
  • You are right. As long as you have bean initialized matching with the class given in method parameter it works.
    – kamoor
    Commented Jan 17, 2015 at 2:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.