问题描述
我正在使用 Spring 3.0.5,并且尽可能为我的班级成员使用 @Autowire 注释.我需要自动装配的 bean 之一需要为其构造函数提供参数.我已经浏览了 Spring 文档,但似乎找不到任何关于如何注释构造函数参数的参考.
I'm using Spring 3.0.5 and am using @Autowire annotation for my class members as much as possible. One of the beans that I need to autowire requires arguments to its constructor. I've looked through the Spring docs, but cannot seem to find any reference to how to annotate constructor arguments.
在 XML 中,我可以将其用作 bean 定义的一部分.@Autowire注解有类似的机制吗?
In XML, I can use as part of the bean definition. Is there a similar mechanism for @Autowire annotation?
例如:
@Component
public class MyConstructorClass{
String var;
public MyConstructorClass( String constrArg ){
this.var = var;
}
...
}
@Service
public class MyBeanService{
@Autowired
MyConstructorClass myConstructorClass;
....
}
在这个例子中,如何使用@Autowire 注释在 MyBeanService 中指定constrArg"的值?有没有办法做到这一点?
In this example, how do I specify the value of "constrArg" in MyBeanService with the @Autowire annotation? Is there any way to do this?
谢谢,
埃里克
推荐答案
您需要 @Value
注释.
You need the @Value
annotation.
一个常见的用例是使用"#{systemProperties.myProp}"
样式表达式.
public class SimpleMovieLister {
private MovieFinder movieFinder;
private String defaultLocale;
@Autowired
public void configure(MovieFinder movieFinder,
@Value("#{ systemProperties['user.region'] }") String defaultLocale) {
this.movieFinder = movieFinder;
this.defaultLocale = defaultLocale;
}
// ...
}
参见: 表达式语言 >注解配置
更明确地说:在您的场景中,您将连接两个类,MybeanService
和 MyConstructorClass
,如下所示:
To be more clear: in your scenario, you'd wire two classes, MybeanService
and MyConstructorClass
, something like this:
@Component
public class MyBeanService implements BeanService{
@Autowired
public MybeanService(MyConstructorClass foo){
// do something with foo
}
}
@Component
public class MyConstructorClass{
public MyConstructorClass(@Value("#{some expression here}") String value){
// do something with value
}
}
更新:如果您需要多个具有不同值的 MyConstructorClass
实例,您应该使用限定符注解
Update: if you need several different instances of MyConstructorClass
with different values, you should use Qualifier annotations
这篇关于有没有办法@Autowire 一个需要构造函数参数的bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!