@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.)
This means it can only be used to annotate constructors, fields, methods, or other annotation types. It can't be used on local variables.
In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file. We have enabled annotation injection.
The @Autowired annotation marks a Constructor, Setter method, Properties and Config() method as to be autowired that is 'injecting beans'(Objects) at runtime by Spring Dependency Injection mechanism which is clearly depicted from the image below as shown: Enabling @Autowired annotation.
Another autowire mode autodetect has been deprecated. Docs says that the “autodetect” option provided too much “magic” and a more explicit declaration is preferred. The default autowire mode in XML configuration is no . The default autowire mode in java configuration is byType .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With