Spring: Using builder pattern to create a bean

Viewed 41279

I use ektorp to connect to CouchDB.

The way to build an ektorp HttpClient instance is to use builder pattern:

HttpClient httpClient = new StdHttpClient.Builder()
                                .host("mychouchdbhost")
                                .port(4455)
                                .build();

I am relatively new to Spring. Please advice me on how I can configure an HttpClient in my context to create it via the Builder.

One way to do this is with @Configuration. Are any other options?

5 Answers

While FactoryBean is cleaner there is a more quick-n-dirty method, using SpEL.

This is how I've just configured the Neo4j driver:

<bean id = "neoDriver" class = "org.neo4j.driver.v1.GraphDatabase" 
        factory-method="driver">
    <constructor-arg value = "bolt://127.0.0.1:7687" />
    <constructor-arg>
        <bean class = "org.neo4j.driver.v1.AuthTokens" factory-method = "basic">
            <constructor-arg value = "neo4j" />
            <constructor-arg value = "***" />
        </bean>
    </constructor-arg>
    <constructor-arg type="org.neo4j.driver.v1.Config" 
        value = "#{T(org.neo4j.driver.v1.Config).build ()
            .withConnectionAcquisitionTimeout ( 10, T(java.util.concurrent.TimeUnit).SECONDS )
            .withConnectionTimeout ( 10, T(java.util.concurrent.TimeUnit).SECONDS )
            .toConfig ()
        }"
    />
</bean>

As you can see from the factory method's 3rd parameter, you can invoke a builder and its methods as a SpEL expression, with the nuance that classes have to be specified via their FQN. But that avoids you to write an entire boilerplate FactoryBean.

Related