Spring annotation @ Methods mentioned inside

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

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

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

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

+8
java spring dependency-injection
source share
2 answers

@Autowired annotation itself annotated with

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

This means that it can only be used to annotate constructors, fields, methods, or other types of annotations. It cannot be used for local variables.

Even if it is possible , nothing Spring or any runtime can do this, because reflection does not provide any bindings in the method bodies. You cannot access this local variable at run time.

You will have to move this local variable to the field and auto-university.

+23
source share

If you are looking for IoC in a 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 notifies user <context:annotation-config />

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

magazine exit

 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 
+1
source share

All Articles