[英]Is it possible to use Spring 3 @Autowired annotation inside @Service?
[英]Spring annotation @Autowired inside methods
@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 in method,您可以这样做:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.