如何将基于java的bean配置转换为基于xml的配置

时间:2016-04-20 13:52:23

标签: java spring

我是一个新手,想知道如何将基于java的配置转换为基于xml的bean配置。我知道基于注释的配置现在更多地使用了一天。但我的要求是使用基于xml的配置。 Bean配置在下面添加。

@Bean
DataStoreWriter<String> dataStoreWriter(org.apache.hadoop.conf.Configuration hadoopConfiguration) {
    TextFileWriter writer = new TextFileWriter(hadoopConfiguration, new Path(basePath), null);
    return writer;

2 个答案:

答案 0 :(得分:1)

From spring doc

  

@Bean是方法级注释,是XML元素的直接模拟。注释支持大多数提供的属性,例如:init-method,destroy-method,autowiring,lazy-init,dependency-check,depends-on和scope。

当您注释方法@bean时,spring容器将执行该方法并将返回值注册为BeanFactory中的bean。默认情况下,bean名称将与方法名称相同。

@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
    return new TransferServiceImpl();
}
}

注意:使用@bean along with @configuration

答案 1 :(得分:1)

您可以直接在xml配置中创建bean

<bean id="dataStoreWriter" class="TextFileWriter">
    <constructor-arg index="0" ref="hadoopConfigBean"/>
    <constructor-arg index="1">
        <bean class="Path">
            <constructor-arg index="0" value="/tmp"/>
        </bean>
    </constructor-arg>
</bean>

如果您需要非平凡的bean配置,那么您可以在xml配置中使用工厂方法调用

<bean id="dataStoreWriter" class="DataStoreFactory" factory-method="dataStoreWriter">
    <constructor-arg index="0" ref="hadoopConfigBean"/>
    <constructor-arg index="1" value="/tmp"/>
</bean>

工厂类应该看起来像

public class DataStoreFactory {

  public static DataStoreWriter<String> dataStoreWriter(Configuration hadoopConfiguration, String basePath) {
    // do something here
    TextFileWriter writer = new TextFileWriter(hadoopConfiguration, new Path(basePath), null);
    return writer;
  }
}
相关问题