问题描述
我正在使用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;
....
}
在此示例中,如何在MyBeanService中使用@Autowire批注指定"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.
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!