2012-10-09 12 views
1

如何讓Spring實例化一個沒有無參數構造函數的bean?我正在使用java-config(而不是xml-config)。它似乎使用XML - 但我不應該能夠以某種方式對註釋做同樣的事情?Spring使用java-config(不是XML)實例化具有構造函數爭論的對象

直接從該教程,下面的例子是在XML的配置等價的:

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

它還提到使用@ConstructorProperties註釋,我已經嘗試過使用 - 但我不能讓它工作。我不斷收到BeanInstantiationException。

+0

請發表您@ConstructorProperties註釋,試圖代碼 –

回答

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

您可以使用@Autowired或@Inject

相關問題