Spring使用java配置(不是XML)实例化具有构造函数参数的对象

Spring使用java配置(不是XML)实例化具有构造函数参数的对象,java,spring,spring-mvc,Java,Spring,Spring Mvc,如何让Spring实例化一个没有无参数构造函数的bean?我使用的是java配置而不是xml配置。它似乎可以使用XML——但我不应该以某种方式在注释上做同样的事情吗 直接从教程中可以看出,以下示例在xml配置中是等效的: <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg index="0" value="7500000"/> <constructor-arg i

如何让Spring实例化一个没有无参数构造函数的bean?我使用的是java配置而不是xml配置。它似乎可以使用XML——但我不应该以某种方式在注释上做同样的事情吗

直接从教程中可以看出,以下示例在xml配置中是等效的:

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg index="0" value="7500000"/>
    <constructor-arg index="1" value="42"/>
</bean>
它还提到了@ConstructorProperties注释的使用,我已经尝试过使用它,但是我无法让它工作。我一直收到一个BeanInstantiationException。

也来自下面的链接


我的理解是,@ConstructorProperties注释不能用作xml配置的替代品。

您可以像在另一个配置中一样使用@Autowired和@Qualifier吗?

您可以使用@Autowired或@Inject

@Configuration
public class MyConfiguration {

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


请发布您使用@ConstructorProperties注释尝试的代码
@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);
    }
}