0

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;

2 Answers 2

1

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;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

How to set null value for the constructor arg CodecInfo in this ?
null value can be passed to argument with special tag <null/> <constructor-arg index="1"><null/></constructor-arg>
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.