Spring Boot – Twilio

Spring Boot – Twilio ”; Previous Next Twilio is a 3rd party application used to send SMS and make voice calls from our application. It allows us to send the SMS and make voice calls programmatically. In this chapter, you are going to learn how to implement the SMS sending and making voice calls by using Spring Boot with Twilio. Note − We used the Trail account in Twilio to send the SMS and making voice calls. You can learn more about Twilio at www.twilio.com. First, we need to add the Twilio dependency in our build configuration file. Maven users can add the following dependency in the pom.xml file. <dependency> <groupId>com.twilio.sdk</groupId> <artifactId>twilio</artifactId> <version>7.16.1</version> </dependency> Gradle users can add the following dependency in the build.gradle file. compile group: “com.twilio.sdk”, name:”twilio”, version: “7.16.1” Now, initialize the Twilio account with ACCOUNT_SID and AUTH_ID in static block as shown − static { Twilio.init(ACCOUNT_SID, AUTH_ID); } Sending SMS To send the SMS, we need to provide a from-number and to-number to the Message.create() method. Message body content also we need to provide for the method Message.creator()as shown − Message.creator(new PhoneNumber(“to-number”), new PhoneNumber(“from-number”), “Message from Spring Boot Application”).create(); The main Spring Boot application class file looks below. package com.tutorialspoint.smsdemo; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.twilio.Twilio; import com.twilio.rest.api.v2010.account.Message; import com.twilio.type.PhoneNumber; @SpringBootApplication public class SmsdemoApplication implements ApplicationRunner { private final static String ACCOUNT_SID = “<your-account-sid>”; private final static String AUTH_ID = “<your-auth-id>”; static { Twilio.init(ACCOUNT_SID, AUTH_ID); } public static void main(String[] args) { SpringApplication.run(SmsdemoApplication.class, args); } @Override public void run(ApplicationArguments arg0) throws Exception { Message.creator(new PhoneNumber(“to-number”), new PhoneNumber(“from-number”), “Message from Spring Boot Application”).create(); } } The complete code to build configuration file is given below − Maven – pom.xml <?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>com.tutorialspoint</groupId> <artifactId>smsdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>smsdemo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.twilio.sdk</groupId> <artifactId>twilio</artifactId> <version>7.16.1</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter”) testCompile(”org.springframework.boot:spring-boot-starter-test”) compile group: “com.twilio.sdk”, name:”twilio”, version: “7.11.+” } You can create an executable JAR file, and run the spring boot application by using the following Maven or Gradle commands − For Maven, use the command as shown − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Run the JAR file by using the command as given below − java –jar <JARFILE> Now, you will receive the SMS to your “to-number”. Message received to “to-number”. Sent from your Twilio trail account – Message from Spring Boot Application Note − In this example, we used the Trail account. So, you should verify the numbers before sending the SMS. Voice Calls To make voice calls by using Twilio, we need to call the Call.creator() method. For this method, we need to provide a to-number, from-number, and voice-note as shown here. Call.creator(new PhoneNumber(“<to-number>”), new PhoneNumber(“<from-number>”), new URI(“http://demo.twilio.com/docs/voice.xml”)).create(); The code for main Spring Boot application class file is given below. package com.tutorialspoint.smsdemo; import java.net.URI; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.twilio.Twilio; import com.twilio.rest.api.v2010.account.Call; import com.twilio.type.PhoneNumber; @SpringBootApplication public class SmsdemoApplication implements ApplicationRunner { private final static String ACCOUNT_SID = “<ACCOUNT-SID>”; private final static String AUTH_ID = “AUTH-ID”; static { Twilio.init(ACCOUNT_SID, AUTH_ID); } public static void main(String[] args) { SpringApplication.run(SmsdemoApplication.class, args); } @Override public void run(ApplicationArguments arg0) throws Exception { Call.creator(new PhoneNumber(“<to-number>”), new PhoneNumber(“<from-number>”), new URI(“http://demo.twilio.com/docs/voice.xml”)).create(); } } The code for complete build configuration file is given below − Maven – pom.xml <?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>com.tutorialspoint</groupId> <artifactId>smsdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>smsdemo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.twilio.sdk</groupId> <artifactId>twilio</artifactId> <version>7.16.1</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter”) testCompile(”org.springframework.boot:spring-boot-starter-test”) compile group: “com.twilio.sdk”, name:”twilio”, version: “7.11.+” } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands. For Maven, use the command as shown − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the command given here − java –jar <JARFILE> Now, you will receive call to your “to-number” from Twilio. Press any key after attending the call, you will hear the voice note from https://demo.twilio.com/docs/voice.xml Note − In this example, we used the Trail account. So, you should verify the numbers before making calls. Print Page Previous Next Advertisements ”;

Spring Boot – Creating Docker Image

Spring Boot – Creating Docker Image ”; Previous Next Docker is a container management service that eases building and deployment. If you are a beginner to Docker, you can learn about is in detail at this link − https://www.tutorialspoint.com/docker/index.htm In this chapter, we are going to see How to create a Docker image by using Maven and Gradle dependencies for your Spring Boot application. Create Dockerfile First, create a file with the name Dockerfile under the directories src/main/docker with the contents shown below. Note that this file is important to create a Docker image. FROM java:8 VOLUME /tmp ADD dockerapp-0.0.1-SNAPSHOT.jar app.jar RUN bash -c ”touch /app.jar” ENTRYPOINT [“java”,”-Djava.security.egd=file:/dev/./urandom”,”-jar”,”/app.jar”] Maven For Maven, add the Docker Maven plugin into your build configuration file pom.xml <properties> <docker.image.prefix>spring-boot-tutorialspoint</docker.image.prefix> </properties> <build> <plugins> <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>1.0.0</version> <configuration> <imageName>${docker.image.prefix}/${project.artifactId}</imageName> <dockerDirectory>src/main/docker</dockerDirectory> <resources> <resource> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resource> </resources> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> The complete pom.xml file is given below − <?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>com.tutorialspoint</groupId> <artifactId>dockerapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>dockerapp</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <docker.image.prefix>spring-boot-tutorialspoint</docker.image.prefix> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>1.0.0</version> <configuration> <imageName>${docker.image.prefix}/${project.artifactId}</imageName> <dockerDirectory>src/main/docker</dockerDirectory> <resources> <resource> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resource> </resources> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Now, you can run your application by using the Maven command mvn package docker:build Note − Enable the Expose daemon on tcp://localhost:2375 without TLS. After build success, you can see the output on the console as shown below − Now, see the Docker images by the command using docker images and see the image info on the console. Gradle To build a Docker image by using Gradle build configuration, we need to add the docker plugin and need to write a task buildDocker to create a Docker image. The code for Gradle Docker configuration is given below. buildscript { ….. dependencies { ….. classpath(”se.transmode.gradle:gradle-docker:1.2”) } } group = ”spring-boot-tutorialspoint” ….. apply plugin: ”docker” task buildDocker(type: Docker, dependsOn: build) { applicationName = jar.baseName dockerfile = file(”src/main/docker/Dockerfile”) doFirst { copy { from jar into stageDir } } } The complete build.gradle file is given below. buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) classpath(”se.transmode.gradle:gradle-docker:1.2”) } } group = ”spring-boot-tutorialspoint” apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” apply plugin: ”docker” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } task buildDocker(type: Docker, dependsOn: build) { applicationName = jar.baseName dockerfile = file(”src/main/docker/Dockerfile”) doFirst { copy { from jar into stageDir } } } Now, create a Docker image by using the command shown below − gradle build buildDocker After executing the command, you can see the BUILD SUCCESSFUL log on the console window. Now, see the Docker images by the command using docker images and see the image’s info on the console. Print Page Previous Next Advertisements ”;

Spring Boot – File Handling

Spring Boot – File Handling ”; Previous Next In this chapter, you will learn how to upload and download the file by using web service. File Upload For uploading a file, you can use MultipartFile as a Request Parameter and this API should consume Multi-Part form data value. Observe the code given below − @RequestMapping(value = “/upload”, method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String fileUpload(@RequestParam(“file”) MultipartFile file) { return null; } The complete code for the same is given below − package com.tutorialspoint.demo.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @RestController public class FileUploadController { @RequestMapping(value = “/upload”, method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String fileUpload(@RequestParam(“file”) MultipartFile file) throws IOException { File convertFile = new File(“/var/tmp/”+file.getOriginalFilename()); convertFile.createNewFile(); FileOutputStream fout = new FileOutputStream(convertFile); fout.write(file.getBytes()); fout.close(); return “File is upload successfully”; } } File Download For file download, you should use InputStreamResource for downloading a File. We need to set the HttpHeader Content-Disposition in Response and need to specify the response Media Type of the application. Note − In the following example, file should be available on the specified path where the application is running. @RequestMapping(value = “/download”, method = RequestMethod.GET) public ResponseEntity<Object> downloadFile() throws IOException { String filename = “/var/tmp/mysql.png”; File file = new File(filename); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); HttpHeaders headers = new HttpHeaders(); headers.add(“Content-Disposition”, String.format(“attachment; filename=”%s””, file.getName())); headers.add(“Cache-Control”, “no-cache, no-store, must-revalidate”); headers.add(“Pragma”, “no-cache”); headers.add(“Expires”, “0”); ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType( MediaType.parseMediaType(“application/txt”)).body(resource); return responseEntity; } The complete code for the same is given below − package com.tutorialspoint.demo.controller; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class FileDownloadController { @RequestMapping(value = “/download”, method = RequestMethod.GET) public ResponseEntity<Object> downloadFile() throws IOException { String filename = “/var/tmp/mysql.png”; File file = new File(filename); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); HttpHeaders headers = new HttpHeaders(); headers.add(“Content-Disposition”, String.format(“attachment; filename=”%s””, file.getName())); headers.add(“Cache-Control”, “no-cache, no-store, must-revalidate”); headers.add(“Pragma”, “no-cache”); headers.add(“Expires”, “0”); ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers).contentLength( file.length()).contentType(MediaType.parseMediaType(“application/txt”)).body(resource); return responseEntity; } } The main Spring Boot application is given below − package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The code for Maven build – pom.xml is given below − <?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>com.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> The code for Gradle Build – build.gradle is given below − buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } Now you can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below − For Maven, use the command given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under target directory. For Gradle, you ca use the command shown below − sgradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory. Now, run the JAR file by using the following command − java –jar <JARFILE> This will start the application on the Tomcat port 8080 as shown below − Now hit the below URL’s in POSTMAN application and you can see the output as shown below − File upload − http://localhost:8080/upload File download − http://localhost:8080/upload Print Page Previous Next Advertisements ”;

Spring Boot – Quick Guide

Spring Boot – Quick Guide ”; Previous Next Spring Boot – Introduction Spring Boot is an open source Java-based framework used to create a micro Service. It is developed by Pivotal Team and is used to build stand-alone and production ready spring applications. This chapter will give you an introduction to Spring Boot and familiarizes you with its basic concepts. What is Micro Service? Micro Service is an architecture that allows the developers to develop and deploy services independently. Each service running has its own process and this achieves the lightweight model to support business applications. Advantages Micro services offers the following advantages to its developers − Easy deployment Simple scalability Compatible with Containers Minimum configuration Lesser production time What is Spring Boot? Spring Boot provides a good platform for Java developers to develop a stand-alone and production-grade spring application that you can just run. You can get started with minimum configurations without the need for an entire Spring configuration setup. Advantages Spring Boot offers the following advantages to its developers − Easy to understand and develop spring applications Increases productivity Reduces the development time Goals Spring Boot is designed with the following goals − To avoid complex XML configuration in Spring To develop a production ready Spring applications in an easier way To reduce the development time and run the application independently Offer an easier way of getting started with the application Why Spring Boot? You can choose Spring Boot because of the features and benefits it offers as given here − It provides a flexible way to configure Java Beans, XML configurations, and Database Transactions. It provides a powerful batch processing and manages REST endpoints. In Spring Boot, everything is auto configured; no manual configurations are needed. It offers annotation-based spring application Eases dependency management It includes Embedded Servlet Container How does it work? Spring Boot automatically configures your application based on the dependencies you have added to the project by using @EnableAutoConfiguration annotation. For example, if MySQL database is on your classpath, but you have not configured any database connection, then Spring Boot auto-configures an in-memory database. The entry point of the spring boot application is the class contains @SpringBootApplication annotation and the main method. Spring Boot automatically scans all the components included in the project by using @ComponentScan annotation. Spring Boot Starters Handling dependency management is a difficult task for big projects. Spring Boot resolves this problem by providing a set of dependencies for developers convenience. For example, if you want to use Spring and JPA for database access, it is sufficient if you include spring-boot-starter-data-jpa dependency in your project. Note that all Spring Boot starters follow the same naming pattern spring-boot-starter- *, where * indicates that it is a type of the application. Examples Look at the following Spring Boot starters explained below for a better understanding − Spring Boot Starter Actuator dependency is used to monitor and manage your application. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> Spring Boot Starter Security dependency is used for Spring Security. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> Spring Boot Starter web dependency is used to write a Rest Endpoints. Its code is shown below − <dependency&gt <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> Spring Boot Starter Thyme Leaf dependency is used to create a web application. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> Spring Boot Starter Test dependency is used for writing Test cases. Its code is shown below − <dependency&gt <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> Auto Configuration Spring Boot Auto Configuration automatically configures your Spring application based on the JAR dependencies you added in the project. For example, if MySQL database is on your class path, but you have not configured any database connection, then Spring Boot auto configures an in-memory database. For this purpose, you need to add @EnableAutoConfiguration annotation or @SpringBootApplication annotation to your main class file. Then, your Spring Boot application will be automatically configured. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @EnableAutoConfiguration public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Spring Boot Application The entry point of the Spring Boot Application is the class contains @SpringBootApplication annotation. This class should have the main method to run the Spring Boot application. @SpringBootApplication annotation includes Auto- Configuration, Component Scan, and Spring Boot Configuration. If you added @SpringBootApplication annotation to the class, you do not need to add the @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration annotation. The @SpringBootApplication annotation includes all other annotations. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Component Scan Spring Boot application scans all the beans and package declarations when the application initializes. You need to add the @ComponentScan annotation for your class file to scan your components added in your project. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.context.annotation.ComponentScan; @ComponentScan public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Spring Boot – Quick Start This chapter will teach you how to create a Spring Boot application using Maven and Gradle. Prerequisites Your system need to have the following minimum requirements to create a Spring Boot application − Java 7 Maven 3.2 Gradle 2.5 Spring Boot CLI The Spring Boot CLI is a command line tool and it allows us to run the Groovy scripts. This is the easiest way to create a Spring Boot application by using the Spring Boot Command Line Interface. You can create, run and test the application in command prompt itself. This section explains you the steps involved in manual installation of Spring Boot CLI. For further help, you can use the following link: https://docs.spring.io/springboot/ docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-springboot You can also download the Spring CLI distribution from the Spring Software repository at: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-manual-cli-installation For manual installation, you need to use the following two folders − spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.tar.gz After the download, unpack

Spring Boot – Scheduling

Spring Boot – Scheduling ”; Previous Next Scheduling is a process of executing the tasks for the specific time period. Spring Boot provides a good support to write a scheduler on the Spring applications. Java Cron Expression Java Cron expressions are used to configure the instances of CronTrigger, a subclass of org.quartz.Trigger. For more information about Java cron expression you can refer to this link − https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. @SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The @Scheduled annotation is used to trigger the scheduler for a specific time period. @Scheduled(cron = “0 * 9 * * ?”) public void cronJobSch() throws Exception { } The following is a sample code that shows how to execute the task every minute starting at 9:00 AM and ending at 9:59 AM, every day package com.tutorialspoint.demo.scheduler; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class Scheduler { @Scheduled(cron = “0 * 9 * * ?”) public void cronJobSch() { SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”); Date now = new Date(); String strDate = sdf.format(now); System.out.println(“Java cron job expression:: ” + strDate); } } The following screenshot shows how the application has started at 09:03:23 and for every one minute from that time the cron job scheduler task has executed. Fixed Rate Fixed Rate scheduler is used to execute the tasks at the specific time. It does not wait for the completion of previous task. The values should be in milliseconds. The sample code is shown here − @Scheduled(fixedRate = 1000) public void fixedRateSch() { } A sample code for executing a task on every second from the application startup is shown here − package com.tutorialspoint.demo.scheduler; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class Scheduler { @Scheduled(fixedRate = 1000) public void fixedRateSch() { SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”); Date now = new Date(); String strDate = sdf.format(now); System.out.println(“Fixed Rate scheduler:: ” + strDate); } } Observe the following screenshot that shows the application that has started at 09:12:00 and after that every second fixed rate scheduler task has executed. Fixed Delay Fixed Delay scheduler is used to execute the tasks at a specific time. It should wait for the previous task completion. The values should be in milliseconds. A sample code is shown here − @Scheduled(fixedDelay = 1000, initialDelay = 1000) public void fixedDelaySch() { } Here, the initialDelay is the time after which the task will be executed the first time after the initial delay value. An example to execute the task for every second after 3 seconds from the application startup has been completed is shown below − package com.tutorialspoint.demo.scheduler; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class Scheduler { @Scheduled(fixedDelay = 1000, initialDelay = 3000) public void fixedDelaySch() { SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”); Date now = new Date(); String strDate = sdf.format(now); System.out.println(“Fixed Delay scheduler:: ” + strDate); } } Observe the following screenshot which shows the application that has started at 09:18:39 and after every 3 seconds, the fixed delay scheduler task has executed on every second. Print Page Previous Next Advertisements ”;

Spring Boot – Hystrix

Spring Boot – Hystrix ”; Previous Next Hystrix is a library from Netflix. Hystrix isolates the points of access between the services, stops cascading failures across them and provides the fallback options. For example, when you are calling a 3rd party application, it takes more time to send the response. So at that time, the control goes to the fallback method and returns the custom response to your application. In this chapter you are going to see How to implement the Hystrix in a Spring Boot application. First, we need to add the Spring Cloud Starter Hystrix dependency in our build configuration file. Maven users can add the following dependency in the pom.xml file − <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency> Gradle users can add the following dependency in the build.gradle file − compile(”org.springframework.cloud:spring-cloud-starter-hystrix”) Now, add the @EnableHystrix annotation into your main Spring Boot application class file. The @EnableHystrix annotation is used to enable the Hystrix functionalities into your Spring Boot application. The main Spring Boot application class file code is given below − package com.tutorialspoint.hystrixapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.hystrix.EnableHystrix; @SpringBootApplication @EnableHystrix public class HystrixappApplication { public static void main(String[] args) { SpringApplication.run(HystrixappApplication.class, args); } } Now write a simple Rest Controller such that it returns the String after 3 seconds from the requested time. @RequestMapping(value = “/”) public String hello() throws InterruptedException { Thread.sleep(3000); return “Welcome Hystrix”; } Now, add the @Hystrix command and @HystrixProperty for the Rest API and define the timeout in milliseconds value. @HystrixCommand(fallbackMethod = “fallback_hello”, commandProperties = { @HystrixProperty(name = “execution.isolation.thread.timeoutInMilliseconds”, value = “1000”) }) Next, define the fallback method fallback_hello() if the request takes a long time to respond. private String fallback_hello() { return “Request fails. It takes long time to response”; } The complete Rest Controller class file that contains REST API and Hystrix properties is shown here − @RequestMapping(value = “/”) @HystrixCommand(fallbackMethod = “fallback_hello”, commandProperties = { @HystrixProperty(name = “execution.isolation.thread.timeoutInMilliseconds”, value = “1000”) }) public String hello() throws InterruptedException { Thread.sleep(3000); return “Welcome Hystrix”; } private String fallback_hello() { return “Request fails. It takes long time to response”; } In this example, REST API written in main Spring Boot application class file itself. package com.tutorialspoint.hystrixapp; import org.springframework.boot.SpringApplication; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; @SpringBootApplication @EnableHystrix @RestController public class HystrixappApplication { public static void main(String[] args) { SpringApplication.run(HystrixappApplication.class, args); } @RequestMapping(value = “/”) @HystrixCommand(fallbackMethod = “fallback_hello”, commandProperties = { @HystrixProperty(name = “execution.isolation.thread.timeoutInMilliseconds”, value = “1000”) }) public String hello() throws InterruptedException { Thread.sleep(3000); return “Welcome Hystrix”; } private String fallback_hello() { return “Request fails. It takes long time to response”; } } The complete build configuration file is given below. Maven – pom.xml file <?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>com.tutorialspoint</groupId> <artifactId>hystrixapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>hystrixapp</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = ”Edgware.RELEASE” } dependencies { compile(”org.springframework.cloud:spring-cloud-starter-hystrix”) compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } dependencyManagement { imports { mavenBom “org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}” } } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands − For Maven, use the command as shown − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the command given below − java –jar <JARFILE> This will start the application on the Tomcat port 8080 as shown below − Now, hit the URL http://localhost:8080/ from your web browser, and see the Hystrix response. The API takes 3 seconds to respond, but Hystrix timeout is 1 second. Print Page Previous Next Advertisements ”;

Spring Boot – Flyway Database

Spring Boot – Flyway Database ”; Previous Next Flyway is a version control application to evolve your Database schema easily and reliably across all your instances. To learn more about Flyway, you can use the link − www.flywaydb.org Many software projects use relational databases. This requires the handling of database migrations, also often called schema migrations. In this chapter, you are going to learn in detail about how to configure Flyway database in your Spring Boot application. Configuring Flyway Database First, download the Spring Boot project from Spring Initializer page www.start.spring.io and choose the following dependencies − Spring Boot Starter Web Flyway MySQL JDBC Maven users can add the following dependencies in pom.xml file. <dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> Gradle users can add the following dependencies in build.gradle file. compile(”org.flywaydb:flyway-core”) compile(”org.springframework.boot:spring-boot-starter-jdbc”) compile(”org.springframework.boot:spring-boot-starter-web”) compile(”mysql:mysql-connector-java”) In application properties, we need to configure the database properties for creating a DataSource and also flyway properties we need to configure in application properties. For properties file users, add the below properties in the application.properties file. spring.application.name = flywayapp spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect=true spring.datasource.username = root spring.datasource.password = root spring.datasource.testOnBorrow = true spring.datasource.testWhileIdle = true spring.datasource.timeBetweenEvictionRunsMillis = 60000 spring.datasource.minEvictableIdleTimeMillis = 30000 spring.datasource.validationQuery = SELECT 1 spring.datasource.max-active = 15 spring.datasource.max-idle = 10 spring.datasource.max-wait = 8000 flyway.url = jdbc:mysql://localhost:3306/mysql flyway.schemas = USERSERVICE flyway.user = root flyway.password = root YAML users can add the following properties in application.yml file. spring: application: name: flywayapp datasource: driverClassName: com.mysql.jdbc.Driver url: “jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect=true” password: “root” username: “root” testOnBorrow: true testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 30000 validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000 flyway: url: jdbc:mysql://localhost:3306/mysql schemas: USERSERVICE user: “root” password: “root” Now, create a SQL file under the src/main/resources/db/migration directory. Name the SQL file as “V1__Initial.sql” CREATE TABLE USERS (ID INT AUTO_INCREMENT PRIMARY KEY, USERID VARCHAR(45)); INSERT INTO USERS (ID, USERID) VALUES (1, ”tutorialspoint.com”); The main Spring Boot application class file code is given below − package com.tutorialspoint.flywayapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FlywayappApplication { public static void main(String[] args) { SpringApplication.run(FlywayappApplication.class, args); } } The complete build configuration file is given below. Maven – pom.xml <?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>com.tutorialspoint</groupId> <artifactId>flywayapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>flywayapp</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.flywaydb:flyway-core”) compile(”org.springframework.boot:spring-boot-starter-jdbc”) compile(”org.springframework.boot:spring-boot-starter-web”) compile(”mysql:mysql-connector-java”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below − For Maven, you can use the command shown here − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command shown here − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the following command − java –jar <JARFILE> Now, Tomcat started on the port 8080 and in the console window you can see the flyway database logs as shown here. You can now go to the database and do the select queries. Print Page Previous Next Advertisements ”;

Spring Boot – Introduction

Spring Boot – Introduction ”; Previous Next Spring Boot is an open source Java-based framework used to create a micro Service. It is developed by Pivotal Team and is used to build stand-alone and production ready spring applications. This chapter will give you an introduction to Spring Boot and familiarizes you with its basic concepts. What is Micro Service? Micro Service is an architecture that allows the developers to develop and deploy services independently. Each service running has its own process and this achieves the lightweight model to support business applications. Advantages Micro services offers the following advantages to its developers − Easy deployment Simple scalability Compatible with Containers Minimum configuration Lesser production time What is Spring Boot? Spring Boot provides a good platform for Java developers to develop a stand-alone and production-grade spring application that you can just run. You can get started with minimum configurations without the need for an entire Spring configuration setup. Advantages Spring Boot offers the following advantages to its developers − Easy to understand and develop spring applications Increases productivity Reduces the development time Goals Spring Boot is designed with the following goals − To avoid complex XML configuration in Spring To develop a production ready Spring applications in an easier way To reduce the development time and run the application independently Offer an easier way of getting started with the application Why Spring Boot? You can choose Spring Boot because of the features and benefits it offers as given here − It provides a flexible way to configure Java Beans, XML configurations, and Database Transactions. It provides a powerful batch processing and manages REST endpoints. In Spring Boot, everything is auto configured; no manual configurations are needed. It offers annotation-based spring application Eases dependency management It includes Embedded Servlet Container How does it work? Spring Boot automatically configures your application based on the dependencies you have added to the project by using @EnableAutoConfiguration annotation. For example, if MySQL database is on your classpath, but you have not configured any database connection, then Spring Boot auto-configures an in-memory database. The entry point of the spring boot application is the class contains @SpringBootApplication annotation and the main method. Spring Boot automatically scans all the components included in the project by using @ComponentScan annotation. Spring Boot Starters Handling dependency management is a difficult task for big projects. Spring Boot resolves this problem by providing a set of dependencies for developers convenience. For example, if you want to use Spring and JPA for database access, it is sufficient if you include spring-boot-starter-data-jpa dependency in your project. Note that all Spring Boot starters follow the same naming pattern spring-boot-starter- *, where * indicates that it is a type of the application. Examples Look at the following Spring Boot starters explained below for a better understanding − Spring Boot Starter Actuator dependency is used to monitor and manage your application. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> Spring Boot Starter Security dependency is used for Spring Security. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> Spring Boot Starter web dependency is used to write a Rest Endpoints. Its code is shown below − <dependency&gt <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> Spring Boot Starter Thyme Leaf dependency is used to create a web application. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> Spring Boot Starter Test dependency is used for writing Test cases. Its code is shown below − <dependency&gt <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> Auto Configuration Spring Boot Auto Configuration automatically configures your Spring application based on the JAR dependencies you added in the project. For example, if MySQL database is on your class path, but you have not configured any database connection, then Spring Boot auto configures an in-memory database. For this purpose, you need to add @EnableAutoConfiguration annotation or @SpringBootApplication annotation to your main class file. Then, your Spring Boot application will be automatically configured. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @EnableAutoConfiguration public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Spring Boot Application The entry point of the Spring Boot Application is the class contains @SpringBootApplication annotation. This class should have the main method to run the Spring Boot application. @SpringBootApplication annotation includes Auto- Configuration, Component Scan, and Spring Boot Configuration. If you added @SpringBootApplication annotation to the class, you do not need to add the @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration annotation. The @SpringBootApplication annotation includes all other annotations. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Component Scan Spring Boot application scans all the beans and package declarations when the application initializes. You need to add the @ComponentScan annotation for your class file to scan your components added in your project. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.context.annotation.ComponentScan; @ComponentScan public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Print Page Previous Next Advertisements ”;

Spring Boot – Tomcat Port Number

Spring Boot – Tomcat Port Number ”; Previous Next Spring Boot lets you to run the same application more than once on a different port number. In this chapter, you will learn about this in detail. Note that the default port number 8080. Custom Port In the application.properties file, we can set custom port number for the property server.port server.port = 9090 In the application.yml file, you can find as follows − server: port: 9090 Random Port In the application.properties file, we can set random port number for the property server.port server.port = 0 In the application.yml file, you can find as follows − server: port: 0 Note − If the server.port number is 0 while starting the Spring Boot application, Tomcat uses the random port number. Print Page Previous Next Advertisements ”;

Zuul Proxy Server and Routing

Spring Boot – Zuul Proxy Server and Routing ”; Previous Next Zuul Server is a gateway application that handles all the requests and does the dynamic routing of microservice applications. The Zuul Server is also known as Edge Server. For Example, /api/user is mapped to the user service and /api/products is mapped to the product service and Zuul Server dynamically routes the requests to the respective backend application. In this chapter, we are going to see in detail how to create Zuul Server application in Spring Boot. Creating Zuul Server Application The Zuul Server is bundled with Spring Cloud dependency. You can download the Spring Boot project from Spring Initializer page https://start.spring.io/ and choose the Zuul Server dependency. Add the @EnableZuulProxy annotation on your main Spring Boot application. The @EnableZuulProxy annotation is used to make your Spring Boot application act as a Zuul Proxy server. package com.tutorialspoint.zuulserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringBootApplication @EnableZuulProxy public class ZuulserverApplication { public static void main(String[] args) { SpringApplication.run(ZuulserverApplication.class, args); } } You will have to add the Spring Cloud Starter Zuul dependency in our build configuration file. Maven users will have to add the following dependency in your pom.xml file − <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> For Gradle users, add the below dependency in your build.gradle file compile(”org.springframework.cloud:spring-cloud-starter-zuul”) For Zuul routing, add the below properties in your application.properties file or application.yml file. spring.application.name = zuulserver zuul.routes.products.path = /api/demo/** zuul.routes.products.url = http://localhost:8080/ server.port = 8111 This means that http calls to /api/demo/ get forwarded to the products service. For example, /api/demo/products is forwarded to /products. yaml file users can use the application.yml file shown below − server: port: 8111 spring: application: name: zuulserver zuul: routes: products: path: /api/demo/** url: http://localhost:8080/ Note − The http://localhost:8080/ application should already be running before routing via Zuul Proxy. The complete build configuration file is given below. Maven users can use the pom.xml file given below − <?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>com.tutorialspoint</groupId> <artifactId>zuulserver</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>zuulserver</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle users can use the build.gradle file given below − buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = ”Edgware.RELEASE” } dependencies { compile(”org.springframework.cloud:spring-cloud-starter-zuul”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } dependencyManagement { imports { mavenBom “org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}” } } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below − For Maven, you can use the command given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command given below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the command shown below − java –jar <JARFILE> You can find the application has started on the Tomcat port 8111 as shown here. Now, hit the URL http://localhost:8111/api/demo/products in your web browser and you can see the output of /products REST Endpoint as shown below − Print Page Previous Next Advertisements ”;