Over a million developers have joined DZone.

Spring Integration with Twitter: How to Post Tweets to Your Twitter Account?

DZone's Guide to

Spring Integration with Twitter: How to Post Tweets to Your Twitter Account?

· Java Zone ·
Free Resource

Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.

Spring Integration provides support for interacting with Twitter. With the Twitter adapters you can both receive and send Twitter messages.

This article provides code snippets and guidelines to post “tweets” to your Twitter account using Spring Integration module.

What you will need to run this tutorial?

  • Twitter Account
  • Twitter oAuth Keys
  • Spring Integration Module
  • Maven
  • An IDE – I am using SpringSource Tool Suite
  • Some spare time

Sign-up For a Twitter Account

Create the Twitter account that you want to use from your application. For this tutorial, I have created an account @SkilledTester.

Twitter Signup Page

Register Your Application

Log into Twitter and register a new application with Twitter at this link.

Twitter - Create an application

Fill in all the required fields and submit the request to create a new Twitter application.

You can leave the “Callaback URL” field as empty. This field is not required for standalone applications.

Once the application is successfully created, you will redirected to the Details Tab as shown below

Twitter - Application Details Page

By default, Access level for the application under OAuth settings is Read-Only. You need to change it so you can also Write and Access Direct Messages.

Click on Settings Tab | Scroll Down to Application Type section and change the access level to Read, Write and Access Direct Messages | click on Update Twitter Application Settings

Twitter - Access Level for Application

Now go back to the Details Tab and confirm that Access Level is changed  to Read, Write and Access Direct Messages.

This step might take couple of minutes to reflect the changes. Once the Access Level is updated, proceed with next steps.

Authorize Your New Application with Twitter

Now, you need to authorize your new Application to access your Twitter Account. This can be done by requesting OAuth Access Token from the Application’s Details Tab

Twitter - Request Access Token

Click on Create my access token.  This will automatically create the access token with the same permission level as of your application.

Your application is now having access to your Twitter Account. You can confirm the same by logging into your Twitter Account and under Settings go to Apps and you will see the new application that we created in the previous step.

At this point you are ready to use your OAuth Consumer Key and Consumer Secret Code along with your Access Token to post updates to your Twitter account.

Now straight into code details.


Twitter Configuration Template

All the Twitter adapters require a Twitter template that will be configured using Spring Java configuration as follows -

package com.skilledmonster.spring.integration.twitter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
 * Spring Java Twitter Configuration Template to configure Twitter Template
 * @author Jagadeesh
public class TwitterConfigurationTemplate {
    private String consumerKey;
    private String consumerSecret;
    private String accessToken;
    private String accessTokenSecret;
    public TwitterTemplate twitterTemplate() {
        TwitterTemplate twitterOperations = new TwitterTemplate(consumerKey,
                consumerSecret, accessToken, accessTokenSecret);
        return twitterOperations;

The twitterTemplate bean requires a set of authorization keys. These can be obtained by placing a request with dev.twitter.com.

Twitter Keys

The Twitter keys are defined in twitter.properties file as shown below. These keys are used to authenticate and authorize the user.

For the purpose of this example, I have posted my SkilledMonster test account authentication and authorization keys.

Account Name: @SkilledTester

Account URL: https://twitter.com/SkilledTester

Consumer key, Consumer secret, Access token and Access token secret are obtained from the Twitter Application Details Tab as already shown above.
# authentication and authorization keys for Twitter account @SkilledTester

Note: Please make sure not to have any empty spaces at the end of key-values.

Spring Configuration for Twitter Update Message

Using Spring Integration, a channel message may be converted into a Twitter update. The outbound-channel-adapter is configured to send the incoming channel message on twitterOutbound to Twitter as an update to @SkilledTester


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    <context:property-placeholder location="/twitter.properties" />
    <int:channel id="twitterOutbound" />
        twitter-template="twitterTemplate" channel="twitterOutbound" />
    <bean id="twitterTemplate"
        <constructor-arg value="${twitter.consumer-key}" />
        <constructor-arg value="${twitter.consumer-secret}" />
        <constructor-arg value="${twitter.access-token}" />
        <constructor-arg value="${twitter.access-token-secret}" />

Note that it is also mandatory to add twitter namespace to the configuration file.

Logger Configuration


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <!-- Appenders -->
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{HH:mm:ss.SSS} %-5p [%t][%c] %m%n" />
    <!-- Loggers -->
    <logger name="com.skilledmonster.spring.integration.twitter">
        <level value="info" />
    <!-- Root Logger -->
        <priority value="warn" />
        <appender-ref ref="console" />

Test Class

I have created the following test class to test Twitter update Spring Configuration. This class simply sends a text message to the twitterOutbound message channel that will post the update to the Twitter account @SkilledTester.

package com.skilledmonster.spring.integration.twitter;
import java.util.Calendar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.message.GenericMessage;
* Sample Test Class to post an update to Twitter Account
* @author Jagadeesh
public class TwitterOutbound {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("/twitter-outbound.xml", TwitterOutbound.class);
        MessageChannel input = context.getBean("twitterOutbound", MessageChannel.class);
        Message message = new GenericMessage(Calendar.getInstance().getTime()+" @ New Message from Skilled Monster using Spring Integration Module");
Note that I am prefixing the message with timestamp because twitter doesn’t allow to post the same update twice in a certain time window.

Twitter Update Posted by Test Class @SkilledTester

Directory Structure

Connect any Java based application to your SaaS data.  Over 100+ Java-based data source connectors.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}