spring servlet example. (#1939)

* spring servlet example.

* add gradle wrapper jar to fix build error.

* rename function and added configurable port number.
- also changed opencensus version to fix the maven build error.
diff --git a/buildscripts/import-control.xml b/buildscripts/import-control.xml
index 1044de7..38e4a67 100644
--- a/buildscripts/import-control.xml
+++ b/buildscripts/import-control.xml
@@ -330,5 +330,6 @@
     <allow pkg="org.apache.log4j"/>
     <allow pkg="org.eclipse.jetty"/>
     <allow pkg="javax.servlet"/>
+    <allow pkg="org.springframework"/>
   </subpackage>
 </import-control>
diff --git a/buildscripts/travis_script b/buildscripts/travis_script
index 8d167c0..c5a0c43 100755
--- a/buildscripts/travis_script
+++ b/buildscripts/travis_script
@@ -54,9 +54,11 @@
     ;;
   "BUILD_EXAMPLES_GRADLE")
     pushd examples && ./gradlew clean assemble --stacktrace && ./gradlew check && ./gradlew verGJF && popd
+    pushd examples/spring/servlet && ./gradlew clean assemble --stacktrace && ./gradlew check && ./gradlew verGJF && popd
     ;;
   "BUILD_EXAMPLES_MAVEN")
     pushd examples && mvn clean package appassembler:assemble -e && popd
+    pushd examples/spring/servlet && mvn clean package appassembler:assemble -e && popd
     ;;
   *)
     echo "Unknown task $TASK"
diff --git a/examples/README.md b/examples/README.md
index 4851da6..1c0b76d 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -12,6 +12,13 @@
 mvn package appassembler:assemble
 ```
 
+To build Spring Servlet example
+```bash
+cd spring/servlet
+mvn package appassembler:assemble
+```
+
+
 ## To run "TagContextExample" use
 
 ### Gradle
@@ -162,3 +169,32 @@
 
 You also need to install and start OpenCensus-Agent in order to receive the traces and metrics.
 For more information on setting up Agent, see [tutorial](https://opencensus.io/agent/).
+
+## To run Spring HTTP Server and Client
+
+`SpringServletApplication` is a web service application using Spring framework. The application
+is instrumented with opencensus simply by incuding opencensus-contrib-spring-starter package.
+The instrumentation enables tracing on incoming and outgoing http requests. On receiving GET 
+request, the server originates multiple GET requests to itself using AsyncRestTemplate on different
+endpoint.
+
+Send a http GET request using curl to see the traces on console.
+```
+curl http://localhost:8080
+```
+
+Stats are available from Prometheus server running at
+- http://localhost:9090/metrics - for server and client stats
+  
+### Gradle
+```bash
+cd spring/servlet
+./gradlew bootRun
+```
+
+### Maven
+```bash
+cd spring/servlet
+./target/appassembler/bin/SpringServletApplication
+```
+
diff --git a/examples/spring/servlet/.gitignore b/examples/spring/servlet/.gitignore
new file mode 100644
index 0000000..51f2f98
--- /dev/null
+++ b/examples/spring/servlet/.gitignore
@@ -0,0 +1,3 @@
+.mvn/**
+mvn**
+
diff --git a/examples/spring/servlet/application.properties b/examples/spring/servlet/application.properties
new file mode 100644
index 0000000..d934d4d
--- /dev/null
+++ b/examples/spring/servlet/application.properties
@@ -0,0 +1,2 @@
+opencensus.spring.enabled = true
+opencensus.spring.trace.publicEndpoint = false
diff --git a/examples/spring/servlet/build.gradle b/examples/spring/servlet/build.gradle
new file mode 100644
index 0000000..515e381
--- /dev/null
+++ b/examples/spring/servlet/build.gradle
@@ -0,0 +1,107 @@
+description = 'OpenCensus Examples Spring Servlet'
+
+buildscript {
+    repositories {
+        mavenCentral()
+        mavenLocal()
+        maven {
+            url "https://plugins.gradle.org/m2/"
+        }
+    }
+    dependencies {
+        classpath 'org.springframework.boot:spring-boot-gradle-plugin:2.0.5.RELEASE'
+        classpath 'com.github.ben-manes:gradle-versions-plugin:0.20.0'
+        classpath "gradle.plugin.com.github.sherter.google-java-format:google-java-format-gradle-plugin:0.8"
+    }
+}
+
+apply plugin: "checkstyle"
+apply plugin: 'com.github.sherter.google-java-format'
+apply plugin: 'idea'
+apply plugin: 'java'
+
+// Display the version report using: ./gradlew dependencyUpdates
+// Also see https://github.com/ben-manes/gradle-versions-plugin.
+apply plugin: 'com.github.ben-manes.versions'
+
+repositories {
+    mavenCentral()
+    mavenLocal()
+}
+
+group = "io.opencensus"
+version = "0.24.0-SNAPSHOT" // CURRENT_OPENCENSUS_VERSION
+
+def opencensusVersion = "0.23.0" // LATEST_OPENCENSUS_RELEASE_VERSION
+def prometheusVersion = "0.6.0"
+def httpasyncclientVersion = "4.1.4"
+
+
+tasks.withType(JavaCompile) {
+    sourceCompatibility = '1.8'
+    targetCompatibility = '1.8'
+}
+
+googleJavaFormat {
+    toolVersion '1.7'
+    source = 'src/main'
+    include '**/*.java'
+}
+
+verifyGoogleJavaFormat {
+    source = 'src/main'
+    include '**/*.java'
+}
+
+// Inform IDEs like IntelliJ IDEA, Eclipse or NetBeans about the generated code.
+sourceSets {
+    main {
+        java {
+            srcDir 'src'
+        }
+    }
+}
+
+checkstyle {
+    configFile = file("$rootDir/../../../buildscripts/checkstyle.xml")
+    toolVersion = "8.12"
+    ignoreFailures = false
+    configProperties["rootDir"] = "$rootDir/../../.."
+}
+
+// Disable checkstyle if no java8.
+checkstyleMain.source = 'src/main'
+checkstyleTest.source = 'src/main'
+buildscript {
+    dependencies {
+        classpath 'org.springframework.boot:spring-boot-gradle-plugin:2.0.5.RELEASE'
+    }
+}
+
+apply plugin: 'java'
+apply plugin: 'org.springframework.boot'
+apply plugin: 'io.spring.dependency-management'
+
+bootJar {
+    mainClassName = 'com.baeldung.Application'
+    baseName = 'opencensus-examples-spring-servlet'
+    version = "0.24.0-SNAPSHOT" // CURRENT_OPENCENSUS_VERSION
+}
+
+sourceCompatibility = 1.8
+targetCompatibility = 1.8
+
+dependencyManagement {
+    imports {
+        mavenBom "io.opencensus:opencensus-contrib-spring-starter:${opencensusVersion}"
+    }
+}
+
+dependencies {
+    compile("io.opencensus:opencensus-contrib-spring-starter:${opencensusVersion}")
+
+    compile("io.opencensus:opencensus-exporter-stats-prometheus:${opencensusVersion}",
+            "io.opencensus:opencensus-exporter-trace-logging:${opencensusVersion}",
+            "io.prometheus:simpleclient_httpserver:${prometheusVersion}",
+            "org.apache.httpcomponents:httpasyncclient:${httpasyncclientVersion}")
+}
diff --git a/examples/spring/servlet/gradle/wrapper/gradle-wrapper.jar b/examples/spring/servlet/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..758de96
--- /dev/null
+++ b/examples/spring/servlet/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/examples/spring/servlet/gradle/wrapper/gradle-wrapper.properties b/examples/spring/servlet/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..a95009c
--- /dev/null
+++ b/examples/spring/servlet/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/examples/spring/servlet/gradlew b/examples/spring/servlet/gradlew
new file mode 100755
index 0000000..cccdd3d
--- /dev/null
+++ b/examples/spring/servlet/gradlew
@@ -0,0 +1,172 @@
+#!/usr/bin/env sh
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn () {
+    echo "$*"
+}
+
+die () {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+  NONSTOP* )
+    nonstop=true
+    ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+    JAVACMD=`cygpath --unix "$JAVACMD"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Escape application args
+save () {
+    for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+    echo " "
+}
+APP_ARGS=$(save "$@")
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
+if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
+  cd "$(dirname "$0")"
+fi
+
+exec "$JAVACMD" "$@"
diff --git a/examples/spring/servlet/gradlew.bat b/examples/spring/servlet/gradlew.bat
new file mode 100644
index 0000000..e95643d
--- /dev/null
+++ b/examples/spring/servlet/gradlew.bat
@@ -0,0 +1,84 @@
+@if "%DEBUG%" == "" @echo off

+@rem ##########################################################################

+@rem

+@rem  Gradle startup script for Windows

+@rem

+@rem ##########################################################################

+

+@rem Set local scope for the variables with windows NT shell

+if "%OS%"=="Windows_NT" setlocal

+

+set DIRNAME=%~dp0

+if "%DIRNAME%" == "" set DIRNAME=.

+set APP_BASE_NAME=%~n0

+set APP_HOME=%DIRNAME%

+

+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.

+set DEFAULT_JVM_OPTS=

+

+@rem Find java.exe

+if defined JAVA_HOME goto findJavaFromJavaHome

+

+set JAVA_EXE=java.exe

+%JAVA_EXE% -version >NUL 2>&1

+if "%ERRORLEVEL%" == "0" goto init

+

+echo.

+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:findJavaFromJavaHome

+set JAVA_HOME=%JAVA_HOME:"=%

+set JAVA_EXE=%JAVA_HOME%/bin/java.exe

+

+if exist "%JAVA_EXE%" goto init

+

+echo.

+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:init

+@rem Get command-line arguments, handling Windows variants

+

+if not "%OS%" == "Windows_NT" goto win9xME_args

+

+:win9xME_args

+@rem Slurp the command line arguments.

+set CMD_LINE_ARGS=

+set _SKIP=2

+

+:win9xME_args_slurp

+if "x%~1" == "x" goto execute

+

+set CMD_LINE_ARGS=%*

+

+:execute

+@rem Setup the command line

+

+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

+

+@rem Execute Gradle

+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

+

+:end

+@rem End local scope for the variables with windows NT shell

+if "%ERRORLEVEL%"=="0" goto mainEnd

+

+:fail

+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of

+rem the _cmd.exe /c_ return code!

+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1

+exit /b 1

+

+:mainEnd

+if "%OS%"=="Windows_NT" endlocal

+

+:omega

diff --git a/examples/spring/servlet/pom.xml b/examples/spring/servlet/pom.xml
new file mode 100644
index 0000000..8486a36
--- /dev/null
+++ b/examples/spring/servlet/pom.xml
@@ -0,0 +1,93 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>io.opencensus</groupId>
+  <artifactId>opencensus-examples-spring-servlet</artifactId>
+  <version>0.24.0-SNAPSHOT</version>
+  <packaging>jar</packaging>
+
+  <properties>
+    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    <!-- change to the version you want to use. -->
+    <apachehttp.version>4.1.4</apachehttp.version>
+    <opencensus.version>0.23.0</opencensus.version><!-- LATEST_OPENCENSUS_RELEASE_VERSION -->
+    <prometheus.version>0.6.0</prometheus.version>
+    <springboot.version>2.0.5.RELEASE</springboot.version>
+    <java.version>1.8</java.version>
+  </properties>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.springframework.boot</groupId>
+      <artifactId>spring-boot-starter-web</artifactId>
+      <version>${springboot.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>io.opencensus</groupId>
+      <artifactId>opencensus-contrib-spring-starter</artifactId>
+      <version>${opencensus.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>io.opencensus</groupId>
+      <artifactId>opencensus-exporter-stats-prometheus</artifactId>
+      <version>${opencensus.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>io.opencensus</groupId>
+      <artifactId>opencensus-exporter-trace-logging</artifactId>
+      <version>${opencensus.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>io.prometheus</groupId>
+      <artifactId>simpleclient_httpserver</artifactId>
+      <version>${prometheus.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.httpcomponents</groupId>
+      <artifactId>httpasyncclient</artifactId>
+      <version>${apachehttp.version}</version>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <extensions>
+      <extension>
+        <groupId>kr.motd.maven</groupId>
+        <artifactId>os-maven-plugin</artifactId>
+        <version>1.5.0.Final</version>
+      </extension>
+    </extensions>
+    <pluginManagement>
+      <plugins>
+        <plugin>
+          <groupId>org.apache.maven.plugins</groupId>
+          <artifactId>maven-compiler-plugin</artifactId>
+          <version>3.7.0</version>
+          <configuration>
+            <source>1.8</source>
+            <target>1.8</target>
+          </configuration>
+        </plugin>
+      </plugins>
+    </pluginManagement>
+    <plugins>
+      <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>appassembler-maven-plugin</artifactId>
+        <version>1.10</version>
+        <configuration>
+          <programs>
+            <program>
+              <id>SpringServletApplication</id>
+              <mainClass>io.opencensus.examples.spring.servlet.Application</mainClass>
+            </program>
+          </programs>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+
+</project>
diff --git a/examples/spring/servlet/settings.gradle b/examples/spring/servlet/settings.gradle
new file mode 100644
index 0000000..4de5678
--- /dev/null
+++ b/examples/spring/servlet/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'opencensus-examples-spring-servlet'
diff --git a/examples/spring/servlet/src/main/java/io/opencensus/examples/spring/servlet/Application.java b/examples/spring/servlet/src/main/java/io/opencensus/examples/spring/servlet/Application.java
new file mode 100644
index 0000000..fba3ba3
--- /dev/null
+++ b/examples/spring/servlet/src/main/java/io/opencensus/examples/spring/servlet/Application.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2019, OpenCensus Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package io.opencensus.examples.spring.servlet;
+
+import io.opencensus.contrib.http.util.HttpViews;
+import io.opencensus.exporter.stats.prometheus.PrometheusStatsCollector;
+import io.opencensus.exporter.trace.logging.LoggingTraceExporter;
+import io.opencensus.trace.Tracing;
+import io.opencensus.trace.config.TraceConfig;
+import io.opencensus.trace.samplers.Samplers;
+import io.prometheus.client.exporter.HTTPServer;
+import java.io.IOException;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.ApplicationContext;
+
+@SpringBootApplication
+public class Application {
+
+  private static void initStatsExporter() throws IOException {
+    HttpViews.registerAllServerViews();
+    HttpViews.registerAllClientViews();
+
+    // Register Prometheus exporters and export metrics to a Prometheus HTTPServer.
+    // Refer to https://prometheus.io/ to run Prometheus Server.
+    PrometheusStatsCollector.createAndRegister();
+    HTTPServer prometheusServer = new HTTPServer(9090, true);
+  }
+
+  private static void initTracingAndLoggingExporter() {
+    TraceConfig traceConfig = Tracing.getTraceConfig();
+    traceConfig.updateActiveTraceParams(
+        traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());
+
+    LoggingTraceExporter.register();
+  }
+
+  /** Main launcher for the SpringServletApplication. */
+  public static void main(String[] args) throws IOException {
+    ApplicationContext ctx = SpringApplication.run(Application.class, args);
+
+    initTracingAndLoggingExporter();
+    initStatsExporter();
+  }
+}
diff --git a/examples/spring/servlet/src/main/java/io/opencensus/examples/spring/servlet/ApplicationAutoConfiguration.java b/examples/spring/servlet/src/main/java/io/opencensus/examples/spring/servlet/ApplicationAutoConfiguration.java
new file mode 100644
index 0000000..deaa67c
--- /dev/null
+++ b/examples/spring/servlet/src/main/java/io/opencensus/examples/spring/servlet/ApplicationAutoConfiguration.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2019, OpenCensus Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package io.opencensus.examples.spring.servlet;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.client.AsyncClientHttpRequestFactory;
+import org.springframework.http.client.HttpComponentsAsyncClientHttpRequestFactory;
+import org.springframework.web.client.AsyncRestTemplate;
+
+@Configuration
+public class ApplicationAutoConfiguration {
+
+  /* Instance of AsyncRestTemplate. */
+  @Bean
+  public AsyncRestTemplate getAsyncRestTemplate(AsyncClientHttpRequestFactory factory) {
+    return new AsyncRestTemplate(factory);
+  }
+
+  /**
+   * Factory for AsyncClientHttpRequest.
+   *
+   * @return AsyncClientHttpRequestFactory
+   */
+  @Bean
+  public AsyncClientHttpRequestFactory getAsyncClientHttpRequestFactory() {
+    int timeout = 5000;
+    HttpComponentsAsyncClientHttpRequestFactory asyncClientHttpRequestFactory =
+        new HttpComponentsAsyncClientHttpRequestFactory();
+    asyncClientHttpRequestFactory.setConnectTimeout(timeout);
+    return asyncClientHttpRequestFactory;
+  }
+}
diff --git a/examples/spring/servlet/src/main/java/io/opencensus/examples/spring/servlet/HelloController.java b/examples/spring/servlet/src/main/java/io/opencensus/examples/spring/servlet/HelloController.java
new file mode 100644
index 0000000..c85a7c5
--- /dev/null
+++ b/examples/spring/servlet/src/main/java/io/opencensus/examples/spring/servlet/HelloController.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2019, OpenCensus Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package io.opencensus.examples.spring.servlet;
+
+import java.util.concurrent.ExecutionException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.client.ClientHttpRequestFactory;
+import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
+import org.springframework.util.concurrent.ListenableFuture;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.AsyncRestTemplate;
+import org.springframework.web.client.RestTemplate;
+
+/* Controller for Web server. */
+@RestController
+public class HelloController {
+  private static final Logger logger = Logger.getLogger(HelloController.class.getName());
+
+  /**
+   * Serves index page.
+   *
+   * @return String
+   */
+  @RequestMapping("/")
+  public String index() {
+    String str = "Hello from servlet instrumented with opencensus-spring";
+    String resp = restTemplate.getForObject("http://localhost:8080/loopback", String.class);
+
+    String asyncUrl = "http://localhost:8080/asyncloopback";
+    ListenableFuture<ResponseEntity<String>> future1 =
+        asyncRestTemplate.getForEntity(asyncUrl, String.class);
+    ListenableFuture<ResponseEntity<String>> future2 =
+        asyncRestTemplate.getForEntity(asyncUrl, String.class);
+    ListenableFuture<ResponseEntity<String>> future3 =
+        asyncRestTemplate.getForEntity(asyncUrl, String.class);
+
+    String resp1 = null;
+    String resp2 = null;
+    String resp3 = null;
+    try {
+      resp1 = future1.get().toString();
+      resp2 = future2.get().toString();
+      resp3 = future3.get().toString();
+    } catch (InterruptedException | ExecutionException e) {
+      logger.log(Level.WARNING, "request failed", e);
+    }
+    return str + resp + "\n" + resp1 + "\n" + resp2 + "\n" + resp3;
+  }
+
+  /* Serves loopback endpoint. */
+  @RequestMapping("/loopback")
+  public String loopback() {
+    return "Loopback. Hello from servlet!";
+  }
+
+  /* Serves asyncloopback endpoint. */
+  @RequestMapping("/asyncloopback")
+  public String asyncLoopback() {
+    return "Async Loopback. Hello from servlet!";
+  }
+
+  @Autowired AsyncRestTemplate asyncRestTemplate;
+
+  RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
+
+  private ClientHttpRequestFactory getClientHttpRequestFactory() {
+    int timeout = 5000;
+    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
+        new HttpComponentsClientHttpRequestFactory();
+    clientHttpRequestFactory.setConnectTimeout(timeout);
+    return clientHttpRequestFactory;
+  }
+}
diff --git a/examples/spring/servlet/src/resources/META-INF/spring.factories b/examples/spring/servlet/src/resources/META-INF/spring.factories
new file mode 100644
index 0000000..4dd75dd
--- /dev/null
+++ b/examples/spring/servlet/src/resources/META-INF/spring.factories
@@ -0,0 +1,3 @@
+# Auto Configuration
+org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
+io.opencensus.examples.spring.servlet.ApplicationAutoConfiguration
diff --git a/examples/spring/servlet/src/resources/application.properties b/examples/spring/servlet/src/resources/application.properties
new file mode 100644
index 0000000..04c0b54
--- /dev/null
+++ b/examples/spring/servlet/src/resources/application.properties
@@ -0,0 +1 @@
+opencensus.spring.trace.propagation=B3
\ No newline at end of file