2. Configuring Twitter Connectivity

Spring Social's ConnectController works with one or more provider-specific ConnectionFactorys to exchange authorization details with the provider and to create connections. Spring Social Twitter provides TwitterConnectionFactory, a ConnectionFactory for creating connections with Twitter.

So that ConnectController can find TwitterConnectionFactory, it must be registered with a ConnectionFactoryRegistry. The following class constructs a ConnectionFactoryRegistry containing a ConnectionFactory for Twitter using Spring's Java configuration style:

@Configuration
public class SocialConfig {

    @Inject
    private Environment environment;
	
    @Bean
    public ConnectionFactoryLocator connectionFactoryLocator() {
        ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
        registry.addConnectionFactory(new TwitterConnectionFactory(
            environment.getProperty("twitter.consumerKey"),
            environment.getProperty("twitter.consumerSecret")));
        return registry;
    }

}

	

Here, a Twitter connection factory is registered with ConnectionFactoryRegistry via the addConnectionFactory() method. If we wanted to add support for connecting to other providers, we would simply register their connection factories here in the same way as TwitterConnectionFactory.

Because consumer keys and secrets may be different across environments (e.g., test, production, etc) it is recommended that these values be externalized. As shown here, Spring 3.1's Environment is used to look up the application's consumer key and secret.

Optionally, you may also configure ConnectionFactoryRegistry and TwitterConnectionFactory in XML:

<bean id="connectionFactoryLocator" class="org.springframework.social.connect.support.ConnectionFactoryRegistry">
    <property name="connectionFactories">
        <list>
            <bean class="org.springframework.social.twitter.connect.TwitterConnectionFactory">
                <constructor-arg value="${twitter.consumerKey}" />
                <constructor-arg value="${twitter.consumerSecret}" />				
            </bean>
        </list>
    </property>
</bean>
	

This is functionally equivalent to the Java-based configuration of ConnectionFactoryRegistry shown before. The only casual difference is that the connection factories are injected as a list into the connectionFactories property rather than with the addConnectionFactory() method. As in the Java-based configuration, the application's consumer key and secret are externalized (shown here as property placeholders).

Refer to Spring Social's reference documentation for complete details on configuring ConnectController and its dependencies.