java Spring 注解@Autowired 内部方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25598406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring annotation @Autowired inside methods
提问by Débora
@Autowired
can be used with constructors, setter and class variables.
@Autowired
可以与构造函数、setter 和类变量一起使用。
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
如何@Autowired
在方法或任何其他范围内使用注释。?我尝试了以下操作,但会产生编译错误。例如
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.)
如果这是不可能的,还有其他方法可以实现吗?(我使用的是 Spring 4。)
回答by Sotirios Delimanolis
The @Autowired
annotation is itself annotated with
该@Autowired
注释本身标注了
@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.
即使可以,Spring 或任何运行时环境也无能为力,因为反射不提供任何方法主体的挂钩。您将无法在运行时访问该局部变量。
You'll have to move that local variable to a field and autowire that.
您必须将该局部变量移动到一个字段并自动装配它。
回答by Jean-Luc Amitousa Mankoy
If what you are looking for is IoC in method you can do this:
如果您正在寻找的是 IoC 方法,您可以这样做:
Helper2.java
class
Helper2.java
班级
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 />
spring.xml
文件通知用户 <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