有没有一种方法@Autowire需要构造函数参数的bean? [英] Is there a way to @Autowire a bean that requires constructor arguments?

查看:460
本文介绍了有没有一种方法@Autowire需要构造函数参数的bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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?

谢谢

埃里克

推荐答案

您需要

You need the @Value annotation.

一个常见的用例是使用 "#{systemProperties.myProp}"样式表达式.

A common use case is to assign default field values using "#{systemProperties.myProp}" style expressions.

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;
  }

  // ...
}

请参阅::更清楚地说:在您的方案中,您将连接两个类MybeanServiceMyConstructorClass,如下所示:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆