@Autowired
可以与构造函数、setter和类变量一起使用。
如何在方法或任何其他范围内使用@Autowired
注释。?我尝试了以下操作,但它会产生编译错误。例如
public classs TestSpring {
public void method(String param){
@Autowired
MyCustomObjct obj;
obj.method(param);
}
}
如果这是不可能的,还有其他方法可以实现吗?(我使用了Spring 4。)
@Autowired
注释本身是用进行注释的
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
这意味着它只能用于注释构造函数、字段、方法或其他注释类型。它不能用于局部变量。
即使可以,Spring或任何运行时环境都无法对此做任何事情,因为反射不提供任何到方法体的挂钩。您将无法在运行时访问该本地变量。
您必须将该局部变量移动到一个字段中,然后自动连接该字段。
如果您正在寻找方法中的IoC,您可以这样做:
Helper2.java
类
public class Helper2 {
@Autowired
ApplicationContext appCxt;
public void tryMe() {
Helper h = (Helper) appCxt.getBean("helper");
System.out.println("Hello: "+h);
}
}
spring.xml
文件通知<context:annotation-config />
的用户
<beans ...>
<context:annotation-config />
<bean id="helper" class="some_spring.Helper" />
<bean id="helper2" class="some_spring.Helper2" />
</beans>
日志输出
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