Spring annotation @Autowired inside methods

15,382

Solution 1

The @Autowired annotation is itself annotated with

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})

This means it can only be used to annotate constructors, fields, methods, or other annotation types. It can't be used on local variables.

Even if it could, there's nothing Spring or any runtime environment could do about it because reflection doesn't provide any hooks into method bodies. You wouldn't be able to access that local variable at runtime.

You'll have to move that local variable to a field and autowire that.

Solution 2

If what you are looking for is IoC in method you can do this:

Helper2.java class

public class Helper2 {

    @Autowired
    ApplicationContext appCxt;

    public void tryMe() {
        Helper h = (Helper) appCxt.getBean("helper");
        System.out.println("Hello: "+h);
    }
}

spring.xml file notice the user of <context:annotation-config />

<beans ...>
    <context:annotation-config />
    <bean id="helper" class="some_spring.Helper" />
    <bean id="helper2" class="some_spring.Helper2" />
</beans>

log output

2017-07-06 01:37:05 DEBUG DefaultListableBeanFactory:249 - Returning cached instance of singleton bean 'helper2'
2017-07-06 01:37:05 DEBUG DefaultListableBeanFactory:249 - Returning cached instance of singleton bean 'helper'
Hello: some_spring.Helper@431e34b2
Share:
15,382

Related videos on Youtube

Débora
Author by

Débora

Updated on September 15, 2022

Comments

  • Débora
    Débora over 1 year

    @Autowired can be used with constructors, setter and class variables.

    How can I use the @Autowired annotation inside a method or any other scope.? I tried the following, but it produces compilation errors. For example

    public classs TestSpring {  
      public void method(String param){  
        @Autowired
        MyCustomObjct obj; 
    
        obj.method(param);
      }
    }  
    

    If this is impossible, is there any other way to achieve ? (I used Spring 4.)