This guide walks you through the process of creating a simple web application that fetches data from Twitter.

What you’ll build

You’ll learn how to build a Spring application that accesses profile data from a Twitter user and from people whom the user follows on Twitter.

What you’ll need

How to complete this guide

Like most Spring Getting Started guides, you can start from scratch and complete each step, or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

To start from scratch, move on to Set up the project.

To skip the basics, do the following:

When you’re finished, you can check your results against the code in gs-accessing-twitter/complete.

Set up the project

First you set up a basic build script. You can use any build system you like when building apps with Spring, but the code you need to work with Gradle and Maven is included here. If you’re not familiar with either, refer to Building Java Projects with Gradle or Building Java Projects with Maven.

Create the directory structure

In a project directory of your choosing, create the following subdirectory structure; for example, with mkdir -p src/main/java/hello on *nix systems:

└── src
    └── main
        └── java
            └── hello

Create a Gradle build file

Below is the initial Gradle build file. But you can also use Maven. The pom.xml file is included right here. If you are using Spring Tool Suite (STS), you can import the guide directly.

If you look at pom.xml, you’ll find it has a specific version of maven-compiler-plugin. This is NOT recommended in general. Instead, it’s meant to solve an issue with our CI system that defaulted to a very old (pre-Java5) version of this plugin. build.gradle
buildscript {
    repositories {
        maven { url "" }
    dependencies {

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-accessing-twitter'
    version =  '0.1.0'

repositories {

dependencies {

task wrapper(type: Wrapper) {
    gradleVersion = '1.11'

The Spring Boot gradle plugin provides many convenient features:

  • It collects all the jars on the classpath and builds a single, runnable "über-jar", which makes it more convenient to execute and transport your service.

  • It searches for the public static void main() method to flag as a runnable class.

  • It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.

Enable Twitter

Before you can fetch a user’s data from Twitter, you must specify your application’s ID and secret by setting the and properties. You can set these via any means supported by Spring Boot, including setting them in an file:

src/main/resources/{{put app ID here}}{{put app secret here}}

As shown here, the properties have fake values. The values given to these properties correspond to your application’s consumer key and secret you obtain when you register the application with Twitter. For the code to work, substitute the real values given to you by Twitter in place of the fake values.

The presence of these properties and Spring Social Twitter in the classpath will trigger automatic configuration of Spring Social’s ConnectController, TwitterConnectionFactory, and other components of Spring Social’s connection framework.

Create connection status views

Although much of what ConnectController does involves redirecting to Twitter and handling a redirect from Twitter, it also shows connection status when a GET request to /connect is made. ConnectController defers to a view named connect/{provider ID}Connect when no existing connection is available and to connect/{providerid}Connected when a connection exists for the provider. In this case, {provider ID} is "twitter".

ConnectController does not define its own connection views, so you need to create them. First, here’s a Thymeleaf view to be shown when no connection to Twitter exists:


		<title>Hello Twitter</title>
		<h3>Connect to Twitter</h3>

		<form action="/connect/twitter" method="POST">
			<div class="formInfo">
				<p>You aren't connected to Twitter yet. Click the button to connect this application with your Twitter account.</p>
			<p><button type="submit">Connect to Twitter</button></p>

The form on this view will POST to /connect/twitter, which is handled by ConnectController and will kick off the OAuth authorization code flow.

Here’s the view to be displayed when a connection exists:


		<title>Hello Twitter</title>
		<h3>Connected to Twitter</h3>

			You are now connected to your Twitter account.
			Click <a href="/">here</a> to see your Twitter friends.

Fetch Twitter data

With Twitter configured in your application, you now can write a Spring MVC controller that fetches data for the user who authorized the application and presents it in the browser. HelloController is just such a controller:


package hello;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

public class HelloController {

    private Twitter twitter;

    private ConnectionRepository connectionRepository;

    public HelloController(Twitter twitter, ConnectionRepository connectionRepository) {
        this.twitter = twitter;
        this.connectionRepository = connectionRepository;

    public String helloTwitter(Model model) {
        if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
            return "redirect:/connect/twitter";

        CursoredList<TwitterProfile> friends = twitter.friendOperations().getFriends();
        model.addAttribute("friends", friends);
        return "hello";


HelloController is created by injecting a Twitter object into its constructor. The Twitter object is a reference to Spring Social’s Twitter API binding.

The helloTwitter() method is annotated with @RequestMapping to indicate that it should handle GET requests for the root path (/). The first thing it does is check to see if the user has authorized the application to access the user’s Twitter data. If not, then the user is redirected to ConnectController with the option to begin the authorization process.

If the user authorizes the application to access the data, the application can fetch almost any data pertaining to the authorizing user. For the purposes of this guide, the application only fetches the user’s profile as well as a list of profiles belonging to Twitter users whom the user follows (but not those who follow the user). Both are placed into the model to be displayed by the view identified as "hello".

Speaking of the "hello" view, here it is as a Thymeleaf template:


		<title>Hello Twitter</title>
		<h3>Hello, <span th:text="${}">Some User</span>!</h3>

		<h4>These are your friends:</h4>

			<li th:each="friend:${friends}" th:text="${}">Friend</li>

This template simply displays a greeting to the user and a list of the user’s friends. Note that even though the full user profiles were fetched, only the names from those profiles are used in this template.

Make the application executable

Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method. And along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.


package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

public class Application {

    public static void main(String[] args) {, args);


The main() method defers to the SpringApplication helper class, providing Application.class as an argument to its run() method. This tells Spring to read the annotation metadata from Application and to manage it as a component in the Spring application context.

The @ComponentScan annotation tells Spring to search recursively through the hello package and its children for classes marked directly or indirectly with Spring’s @Component annotation. This directive ensures that Spring finds and registers the GreetingController, because it is marked with @Controller, which in turn is a kind of @Component annotation.

The @Import annotation tells Spring to import additional Java configuration. Here it is asking Spring to import the TwitterConfig class where you enabled Twitter in your application.

The @EnableAutoConfiguration annotation switches on reasonable default behaviors based on the content of your classpath. For example, because the application depends on the embeddable version of Tomcat (tomcat-embed-core.jar), a Tomcat server is set up and configured with reasonable defaults on your behalf. And because the application also depends on Spring MVC (spring-webmvc.jar), a Spring MVC DispatcherServlet is configured and registered for you — no web.xml necessary! Auto-configuration is a powerful, flexible mechanism. See the API documentation for further details.

Build an executable JAR

You can build a single executable JAR file that contains all the necessary dependencies, classes, and resources. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

./gradlew build

Then you can run the JAR file:

java -jar build/libs/gs-accessing-twitter-0.1.0.jar

If you are using Maven, you can run the application using mvn spring-boot:run. Or you can build the JAR file with mvn clean package and run the JAR by typing:

java -jar target/gs-accessing-twitter-0.1.0.jar
The procedure above will create a runnable JAR. You can also opt to build a classic WAR file instead.

Run the service

If you are using Gradle, you can run your service at the command line this way:

./gradlew clean build && java -jar build/libs/gs-accessing-twitter-0.1.0.jar
If you are using Maven, you can run your service by typing mvn clean package && java -jar target/gs-accessing-twitter-0.1.0.jar.

You can alternatively run the app directly from Gradle like this:

./gradlew bootRun
With mvn, you can run mvn spring-boot:run.
... app starts up ...

Once the application starts up, you can point your web browser to http://localhost:8080. Because no connection is established yet, you see this screen prompting you to connect with Twitter:

No connection to Twitter exists yet.

When you click Connect to Twitter, the browser is redircted to Twitter for authorization:

Twitter needs your permission to allow the application to access your data.

At this point, Twitter asks if you’d like to allow the sample application to read tweets from your profile and see who you follow. Here the screen is misleading, because the application in this case will only read your profile details and the profile details of the people you follow. Click Authorize app to grant permission.

Once permission is granted, Twitter redirects the browser to the application. A connection is created and stored in the connection repository. You should see this page indicating that a connection was successful:

A connection with Twitter has been created.

If you click on the link on the connection status page, you are taken to the home page. This time, now that a connection exists, you see your name on Twitter and a list of your friends:

Guess noone told you life was gonna be this way.


Congratulations! You’ve developed a simple web application that uses Spring Social to obtain user authorization to fetch data from the user’s Twitter profile and from the profiles of people whom the user follows.