1

如何让 Spring 实例化一个没有无参数构造函数的 bean?我正在使用 java-config(不是 xml-config)。它似乎使用 XML 工作 - 但我不应该能够以某种方式对注释做同样的事情吗?

直接来自教程,以下示例是 xml-config 中的等效示例:

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg index="0" value="7500000"/>
    <constructor-arg index="1" value="42"/>
</bean>

它还提到了@ConstructorProperties 注释的使用,我尝试使用它 - 但我无法让它工作。我不断收到 BeanInstantiationException。

4

4 回答 4

0

也来自下面的链接 http://docs.oracle.com/javase/6/docs/api/java/beans/ConstructorProperties.html

我的理解是,@ConstructorProperties 注释不能用作您的 xml-config 的替代品。

于 2012-10-09T15:12:43.490 回答
0

你可以像在另一篇SO 文章@Autowired中那样使用with吗?@Qualifier

于 2012-10-09T15:19:16.087 回答
0

您可以使用@Autowired 或@Inject

于 2012-10-09T16:53:29.170 回答
0
@Configuration
public class MyConfiguration {

    @Bean
    public ExampleBean exampleBean() {
        return new ExampleBean(7500000, 42);
    }
}

或者:

@Configuration
@PropertySource(value = { "my.properties" })
public class MyConfiguration {

    @Value("{prop.value1}")
    private int value1;
    @Value("{prop.value2}")
    private int value2;

    @Bean
    public ExampleBean exampleBean() {
        return new ExampleBean(value1, value2);
    }
}
于 2012-10-09T17:21:21.087 回答