【问题标题】:Spring annotation @Autowired inside methodsSpring注解@Autowired内部方法
【发布时间】:2014-10-25 05:51:18
【问题描述】:
@Autowired 可以与构造函数、setter 和类变量一起使用。
如何在方法或任何其他范围内使用@Autowired 注释?我尝试了以下方法,但它会产生编译错误。例如
public classs TestSpring {
public void method(String param){
@Autowired
MyCustomObjct obj;
obj.method(param);
}
}
如果这是不可能的,还有其他方法可以实现吗? (我用的是 Spring 4。)
【问题讨论】:
标签:
java
spring
dependency-injection
【解决方案1】:
如果您正在寻找的方法是 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
【解决方案2】:
@Autowired 注释本身带有注释
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
这意味着它只能用于注释构造函数、字段、方法或其他注释类型。它不能用于局部变量。
即使可以,Spring 或任何运行时环境也无能为力,因为反射不提供任何方法体的挂钩。您将无法在运行时访问该局部变量。
您必须将该局部变量移动到一个字段并自动装配它。