Sachin
Sachin

Reputation: 1715

How to convert java based bean configuration to xml based config

I'm a newbie to spring and wonder how java based configs can be converted to xml based bean configs. I know that annotation based configs are more used now a days. But my requirement is to use xml based configs. Bean configuration is added below.

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

Upvotes: 0

Views: 897

Answers (2)

Andrew Kolpakov
Andrew Kolpakov

Reputation: 439

You can create bean directly in xml configuration

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

If you need non-trivial bean configuration then you can use factory method call in xml configuration

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

Factory class should look like

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

Upvotes: 1

Ramesh Papaganti
Ramesh Papaganti

Reputation: 7831

From spring doc

@Bean is a method-level annotation and a direct analog of the XML element. The annotation supports most of the attributes offered by , such as: init-method, destroy-method, autowiring, lazy-init, dependency-check, depends-on and scope.

When you annotate method @bean spring container will execute that method and register the return value as a bean within a BeanFactory. By default, the bean name will be the same as the method name.

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

Note :Use @bean along with @configuration

Upvotes: 1

Related Questions