Spring Boot – Actuator ”; Previous Next Spring Boot Actuator provides secured endpoints for monitoring and managing your Spring Boot application. By default, all actuator endpoints are secured. In this chapter, you will learn in detail about how to enable Spring Boot actuator to your application. Enabling Spring Boot Actuator To enable Spring Boot actuator endpoints to your Spring Boot application, we need to add the Spring Boot Starter actuator dependency in our build configuration file. Maven users can add the below dependency in your pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> Gradle users can add the below dependency in your build.gradle file. compile group: ”org.springframework.boot”, name: ”spring-boot-starter-actuator” In the application.properties file, we need to disable the security for actuator endpoints. management.security.enabled = false YAML file users can add the following property in your application.yml file. management: security: enabled: false If you want to use the separate port number for accessing the Spring boot actutator endpoints add the management port number in application.properties file. management.port = 9000 YAML file users can add the following property in your application.yml file. management: port: 9000 Now, you can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands. For Maven, you can use the following command − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the following command − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, you can run the JAR file by using the following command − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080. Note that if you specified the management port number, then same application is running on two different port numbers. Some important Spring Boot Actuator endpoints are given below. You can enter them in your web browser and monitor your application behavior. ENDPOINTS USAGE /metrics To view the application metrics such as memory used, memory free, threads, classes, system uptime etc. /env To view the list of Environment variables used in the application. /beans To view the Spring beans and its types, scopes and dependency. /health To view the application health /info To view the information about the Spring Boot application. /trace To view the list of Traces of your Rest endpoints. Print Page Previous Next Advertisements ”;
Category: spring Boot
Spring Boot – Database Handling ”; Previous Next Spring Boot provides a very good support to create a DataSource for Database. We need not write any extra code to create a DataSource in Spring Boot. Just adding the dependencies and doing the configuration details is enough to create a DataSource and connect the Database. In this chapter, we are going to use Spring Boot JDBC driver connection to connect the database. First, we need to add the Spring Boot Starter JDBC dependency in our build configuration file. Maven users can add the following dependencies in the pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> Gradle users can add the following dependencies in the build.gradle file. compile(”org.springframework.boot:spring-boot-starter-jdbc”) Connect to H2 database To connect the H2 database, we need to add the H2 database dependency in our build configuration file. For Maven users, add the below dependency in your pom.xml file. <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> For Gradle users, add the below dependency in your build.gradle file. compile(”com.h2database:h2”) We need to create the schema.sql file and data.sql file under the classpath src/main/resources directory to connect the H2 database. The schema.sql file is given below. CREATE TABLE PRODUCT (ID INT PRIMARY KEY, PRODUCT_NAME VARCHAR(25)); The data.sql file is given below. INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (1,”Honey”); INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (2,”Almond”); Connect MySQL To connect the MySQL database, we need to add the MySQL dependency into our build configuration file. For Maven users, add the following dependency in your pom.xml file. <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> For Gradle users, add the following dependency in your build.gradle file. compile(”mysql:mysql-connector-java”) Now, create database and tables in MySQL as shown − For properties file users, add the following properties in the application.properties file. spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?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 For YAML users, add the following properties in the application.yml file. spring: datasource: driverClassName: com.mysql.jdbc.Driver url: “jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect=true” username: “root” password: “root” testOnBorrow: true testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 30000 validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000 Connect Redis Redis is an open source database used to store the in-memory data structure. To connect the Redis database in Spring Boot application, we need to add the Redis dependency in our build configuration file. Maven users should add the following dependency in your pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> Gradle users should add the following dependency in your build.gradle file. compile(”org.springframework.boot:spring-boot-starter-data-redis”) For Redis connection, we need to use RedisTemplate. For RedisTemplate we need to provide the JedisConnectionFactory details. @Bean JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory jedisConFactory = new JedisConnectionFactory(); jedisConFactory.setHostName(“localhost”); jedisConFactory.setPort(6000); jedisConFactory.setUsePool(true); return jedisConFactory; } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(jedisConnectionFactory()); template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new StringRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); return template; } Now auto wire the RedisTemplate class and access the data from Redis database. @Autowired RedisTemplate<String, Object> redis; Map<Object,Object> datalist = redis.opsForHash().entries(“Redis_code_index_key”); JDBCTemplate To access the Relational Database by using JdbcTemplate in Spring Boot application, we need to add the Spring Boot Starter JDBC dependency in our build configuration file. Then, if you @Autowired the JdbcTemplate class, Spring Boot automatically connects the Database and sets the Datasource for the JdbcTemplate object. @Autowired JdbcTemplate jdbcTemplate; Collection<Map<String, Object>> rows = jdbc.queryForList(“SELECT QUERY”); The @Repository annotation should be added into the class file. The @Repository annotation is used to create database repository for your Spring Boot application. @Repository public class ProductServiceDAO { } Multiple DataSource We can keep ‘n’ number Datasources in a single Spring Boot application. The example given here shows how to create more than 1 data source in Spring Boot application. Now, add the two data source configuration details in the application properties file. For properties file users, add the following properties into your application.properties file. spring.dbProductService.driverClassName = com.mysql.jdbc.Driver spring.dbProductService.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = true spring.dbProductService.username = root spring.dbProductService.password = root spring.dbProductService.testOnBorrow = true spring.dbProductService.testWhileIdle = true spring.dbProductService.timeBetweenEvictionRunsMillis = 60000 spring.dbProductService.minEvictableIdleTimeMillis = 30000 spring.dbProductService.validationQuery = SELECT 1 spring.dbProductService.max-active = 15 spring.dbProductService.max-idle = 10 spring.dbProductService.max-wait = 8000 spring.dbUserService.driverClassName = com.mysql.jdbc.Driver spring.dbUserService.url = jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect = true spring.dbUserService.username = root spring.dbUserService.password = root spring.dbUserService.testOnBorrow = true spring.dbUserService.testWhileIdle = true spring.dbUserService.timeBetweenEvictionRunsMillis = 60000 spring.dbUserService.minEvictableIdleTimeMillis = 30000 spring.dbUserService.validationQuery = SELECT 1 spring.dbUserService.max-active = 15 spring.dbUserService.max-idle = 10 spring.dbUserService.max-wait = 8000 Yaml users should add the following properties in your application.yml file. spring: dbProductService: driverClassName: com.mysql.jdbc.Driver url: “jdbc:mysql://localhost:3306/PRODUCTSERVICE?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 dbUserService: 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 Now, create a Configuration class to create a DataSource and JdbcTemplate for multiple data sources. import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class DatabaseConfig { @Bean(name = “dbProductService”) @ConfigurationProperties(prefix = “spring.dbProductService”) @Primary public DataSource createProductServiceDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = “dbUserService”) @ConfigurationProperties(prefix = “spring.dbUserService”) public DataSource createUserServiceDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = “jdbcProductService”) @Autowired public JdbcTemplate createJdbcTemplate_ProductService(@Qualifier(“dbProductService”) DataSource productServiceDS) { return new JdbcTemplate(productServiceDS); } @Bean(name = “jdbcUserService”) @Autowired public JdbcTemplate createJdbcTemplate_UserService(@Qualifier(“dbUserService”) DataSource userServiceDS) { return new JdbcTemplate(userServiceDS); } } Then, auto wire the JDBCTemplate object by using @Qualifier annotation. @Qualifier(“jdbcProductService”) @Autowired JdbcTemplate jdbcTemplate; @Qualifier(“jdbcUserService”) @Autowired JdbcTemplate jdbcTemplate; Print Page Previous Next Advertisements ”;
Spring Boot – Admin Server
Spring Boot – Admin Server ”; Previous Next Monitoring your application by using Spring Boot Actuator Endpoint is slightly difficult. Because, if you have ‘n’ number of applications, every application has separate actuator endpoints, thus making monitoring difficult. Spring Boot Admin Server is an application used to manage and monitor your Microservice application. To handle such situations, CodeCentric Team provides a Spring Boot Admin UI to manage and monitor all your Spring Boot application Actuator endpoints at one place. For building a Spring Boot Admin Server we need to add the below dependencies in your build configuration file. Maven users can add the below dependencies in your pom.xml file − <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server-ui</artifactId> <version>1.5.5</version> </dependency> Gradle users can add the below dependencies in your build.gradle file − compile group: ”de.codecentric”, name: ”spring-boot-admin-server”, version: ”1.5.5” compile group: ”de.codecentric”, name: ”spring-boot-admin-server-ui”, version: ”1.5.5” Add the @EnableAdminServer annotation in your main Spring Boot application class file. The @EnableAdminServer annotation is used to make your as Admin Server to monitor all other microservices. package com.tutorialspoint.adminserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import de.codecentric.boot.admin.config.EnableAdminServer; @SpringBootApplication @EnableAdminServer public class AdminserverApplication { public static void main(String[] args) { SpringApplication.run(AdminserverApplication.class, args); } } Now, define the server.port and application name in application.properties file a shown − server.port = 9090 spring.application.name = adminserver For YAML users, use the following properties to define the port number and application name in application.yml file. server: port: 9090 spring: application: name: adminserver The build configuration file is given below. For Maven users – 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>adminserver</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>adminserver</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>de.codecentric</groupId> <artifactId>spring-boot-admin-server</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server-ui</artifactId> <version>1.5.5</version> </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> For Gradle users – build.gradle file 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”) compile group: ”de.codecentric”, name: ”spring-boot-admin-server”, version: ”1.5.5” compile group: ”de.codecentric”, name: ”spring-boot-admin-server-ui”, version: ”1.5.5” testCompile(”org.springframework.boot:spring-boot-starter-test”) } 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 shown here − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under target directory. For Gradle, use the command shown here − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory. Now, run the JAR file by using the command given below − java –jar <JARFILE> Now, the application has started on the Tomcat port 9090 as shown here − Now hit the below URL from your web browser and see the Admin Server UI. http://localhost:9090/ Print Page Previous Next Advertisements ”;
Spring Boot – Logging
Spring Boot – Logging ”; Previous Next Spring Boot uses Apache Commons logging for all internal logging. Spring Boot’s default configurations provides a support for the use of Java Util Logging, Log4j2, and Logback. Using these, we can configure the console logging as well as file logging. If you are using Spring Boot Starters, Logback will provide a good support for logging. Besides, Logback also provides a use of good support for Common Logging, Util Logging, Log4J, and SLF4J. Log Format The default Spring Boot Log format is shown in the screenshot given below. which gives you the following information − Date and Time that gives the date and time of the log Log level shows INFO, ERROR or WARN Process ID The — which is a separator Thread name is enclosed within the square brackets [] Logger Name that shows the Source class name The Log message Console Log Output The default log messages will print to the console window. By default, “INFO”, “ERROR” and “WARN” log messages will print in the log file. If you have to enable the debug level log, add the debug flag on starting your application using the command shown below − java –jar demo.jar –debug You can also add the debug mode to your application.properties file as shown here − debug = true File Log Output By default, all logs will print on the console window and not in the files. If you want to print the logs in a file, you need to set the property logging.file or logging.path in the application.properties file. You can specify the log file path using the property shown below. Note that the log file name is spring.log. logging.path = /var/tmp/ You can specify the own log file name using the property shown below − logging.file = /var/tmp/mylog.log Note − files will rotate automatically after reaching the size 10 MB. Log Levels Spring Boot supports all logger levels such as “TRACE”, “DEBUG”, “INFO”, “WARN”, “ERROR”, “FATAL”, “OFF”. You can define Root logger in the application.properties file as shown below − logging.level.root = WARN Note − Logback does not support “FATAL” level log. It is mapped to the “ERROR” level log. Configure Logback Logback supports XML based configuration to handle Spring Boot Log configurations. Logging configuration details are configured in logback.xml file. The logback.xml file should be placed under the classpath. You can configure the ROOT level log in Logback.xml file using the code given below − <?xml version = “1.0” encoding = “UTF-8”?> <configuration> <root level = “INFO”> </root> </configuration> You can configure the console appender in Logback.xml file given below. <?xml version = “1.0” encoding = “UTF-8”?> <configuration> <appender name = “STDOUT” class = “ch.qos.logback.core.ConsoleAppender”></appender> <root level = “INFO”> <appender-ref ref = “STDOUT”/> </root> </configuration> You can configure the file appender in Logback.xml file using the code given below. Note that you need to specify the Log file path insider the file appender. <?xml version = “1.0” encoding = “UTF-8”?> <configuration> <appender name = “FILE” class = “ch.qos.logback.core.FileAppender”> <File>/var/tmp/mylog.log</File> </appender> <root level = “INFO”> <appender-ref ref = “FILE”/> </root> </configuration> You can define the Log pattern in logback.xml file using the code given below. You can also define the set of supported log patterns inside the console or file log appender using the code given below − <pattern>[%d{yyyy-MM-dd”T”HH:mm:ss.sss”Z”}] [%C] [%t] [%L] [%-5p] %m%n</pattern> The code for complete logback.xml file is given below. You have to place this in the class path. <?xml version = “1.0” encoding = “UTF-8”?> <configuration> <appender name = “STDOUT” class = “ch.qos.logback.core.ConsoleAppender”> <encoder> <pattern>[%d{yyyy-MM-dd”T”HH:mm:ss.sss”Z”}] [%C] [%t] [%L] [%-5p] %m%n</pattern> </encoder> </appender> <appender name = “FILE” class = “ch.qos.logback.core.FileAppender”> <File>/var/tmp/mylog.log</File> <encoder> <pattern>[%d{yyyy-MM-dd”T”HH:mm:ss.sss”Z”}] [%C] [%t] [%L] [%-5p] %m%n</pattern> </encoder> </appender> <root level = “INFO”> <appender-ref ref = “FILE”/> <appender-ref ref = “STDOUT”/> </root> </configuration> The code given below shows how to add the slf4j logger in Spring Boot main class file. package com.tutorialspoint.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class); public static void main(String[] args) { logger.info(“this is a info message”); logger.warn(“this is a warn message”); logger.error(“this is a error message”); SpringApplication.run(DemoApplication.class, args); } } The output that you can see in the console window is shown here − The output that you can see in the log file is shown here − Print Page Previous Next Advertisements ”;
Consuming RESTful Web Services ”; Previous Next This chapter will discuss in detail about consuming a RESTful Web Services by using jQuery AJAX. Create a simple Spring Boot web application and write a controller class files which is used to redirects into the HTML file to consumes the RESTful web services. We need to add the Spring Boot starter Thymeleaf and Web dependency in our build configuration file. For Maven users, add the below dependencies in your pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> For Gradle users, add the below dependencies into your build.gradle file − compile group: ‘org.springframework.boot’, name: ‘spring-boot-starter-thymeleaf’ compile(‘org.springframework.boot:spring-boot-starter-web’) The code for @Controller class file is given below − @Controller public class ViewController { } You can define the Request URI methods to redirects into the HTML file as shown below − @RequestMapping(“/view-products”) public String viewProducts() { return “view-products”; } @RequestMapping(“/add-products”) public String addProducts() { return “add-products”; } This API http://localhost:9090/products should return the below JSON in response as shown below − [ { “id”: “1”, “name”: “Honey” }, { “id”: “2”, “name”: “Almond” } ] Now, create a view-products.html file under the templates directory in the classpath. In the HTML file, we added the jQuery library and written the code to consume the RESTful web service on page load. <script src = “https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script> <script> $(document).ready(function(){ $.getJSON(“http://localhost:9090/products”, function(result){ $.each(result, function(key,value) { $(“#productsJson”).append(value.id+” “+value.name+” “); }); }); }); </script> The POST method and this URL http://localhost:9090/products should contains the below Request Body and Response body. The code for Request body is given below − { “id”:”3″, “name”:”Ginger” } The code for Response body is given below − Product is created successfully Now, create the add-products.html file under the templates directory in the classpath. In the HTML file, we added the jQuery library and written the code that submits the form to RESTful web service on clicking the button. <script src = “https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script> <script> $(document).ready(function() { $(“button”).click(function() { var productmodel = { id : “3”, name : “Ginger” }; var requestJSON = JSON.stringify(productmodel); $.ajax({ type : “POST”, url : “http://localhost:9090/products”, headers : { “Content-Type” : “application/json” }, data : requestJSON, success : function(data) { alert(data); }, error : function(data) { } }); }); }); </script> The complete code 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>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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </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.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’) compile group: ‘org.springframework.boot’, name: ‘spring-boot-starter-thymeleaf’ testCompile(‘org.springframework.boot:spring-boot-starter-test’) } The controller class file given below – ViewController.java is given below − package com.tutorialspoint.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ViewController { @RequestMapping(“/view-products”) public String viewProducts() { return “view-products”; } @RequestMapping(“/add-products”) public String addProducts() { return “add-products”; } } The view-products.html file is given below − <!DOCTYPE html> <html> <head> <meta charset = “ISO-8859-1″/> <title>View Products</title> <script src = “https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script> <script> $(document).ready(function(){ $.getJSON(“http://localhost:9090/products”, function(result){ $.each(result, function(key,value) { $(“#productsJson”).append(value.id+” “+value.name+” “); }); }); }); </script> </head> <body> <div id = “productsJson”> </div> </body> </html> The add-products.html file is given below − <!DOCTYPE html> <html> <head> <meta charset = “ISO-8859-1” /> <title>Add Products</title> <script src = “https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script> <script> $(document).ready(function() { $(“button”).click(function() { var productmodel = { id : “3”, name : “Ginger” }; var requestJSON = JSON.stringify(productmodel); $.ajax({ type : “POST”, url : “http://localhost:9090/products”, headers : { “Content-Type” : “application/json” }, data : requestJSON, success : function(data) { alert(data); }, error : function(data) { } }); }); }); </script> </head> <body> <button>Click here to submit the form</button> </body> </html> The main Spring Boot Application class file 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); } } Now, 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 given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the command as given below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Run the JAR file by using the following command − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080. Now hit the URL in your web browser and you can see the output as shown − http://localhost:8080/view-products http://localhost:8080/add-products Now, click the button Click here to submit the form and you can see the result as shown − Now, hit the view products URL and see the created product. http://localhost:8080/view-products Angular JS To consume the APIs by using Angular JS, you can use the examples given below − Use the following code to create the Angular JS Controller to consume the GET API – http://localhost:9090/products − angular.module(”demo”, []) .controller(”Hello”, function($scope, $http) { $http.get(”http://localhost:9090/products”). then(function(response) { $scope.products = response.data; }); }); Use the following code to create the Angular JS Controller to consume the POST API – http://localhost:9090/products − angular.module(”demo”, []) .controller(”Hello”, function($scope, $http) { $http.post(”http://localhost:9090/products”,data). then(function(response) { console.log(“Product created successfully”); }); }); Note − The Post method data represents the Request body in JSON format to create a product. Print Page Previous Next Advertisements ”;
Spring Boot – CORS Support
Spring Boot – CORS Support ”; Previous Next Cross-Origin Resource Sharing (CORS) is a security concept that allows restricting the resources implemented in web browsers. It prevents the JavaScript code producing or consuming the requests against different origin. For example, your web application is running on 8080 port and by using JavaScript you are trying to consuming RESTful web services from 9090 port. Under such situations, you will face the Cross-Origin Resource Sharing security issue on your web browsers. Two requirements are needed to handle this issue − RESTful web services should support the Cross-Origin Resource Sharing. RESTful web service application should allow accessing the API(s) from the 8080 port. In this chapter, we are going to learn in detail about How to Enable Cross-Origin Requests for a RESTful Web Service application. Enable CORS in Controller Method We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application. @RequestMapping(value = “/products”) @CrossOrigin(origins = “http://localhost:8080”) public ResponseEntity<Object> getProduct() { return null; } Global CORS Configuration We need to define the shown @Bean configuration to set the CORS configuration support globally to your Spring Boot application. @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping(“/products”).allowedOrigins(“http://localhost:9000”); } }; } To code to set the CORS configuration globally in main Spring Boot application is given below. package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping(“/products”).allowedOrigins(“http://localhost:8080″); } }; } } Now, you can create a Spring Boot web application that runs on 8080 port and your RESTful web service application that can run on the 9090 port. For further details about implementation about RESTful Web Service, you can refer to the chapter titled Consuming RESTful Web Services of this tutorial. Print Page Previous Next Advertisements ”;
Spring Boot – Interceptor
Spring Boot – Interceptor ”; Previous Next You can use the Interceptor in Spring Boot to perform operations under the following situations − Before sending the request to the controller Before sending the response to the client For example, you can use an interceptor to add the request header before sending the request to the controller and add the response header before sending the response to the client. To work with interceptor, you need to create @Component class that supports it and it should implement the HandlerInterceptor interface. The following are the three methods you should know about while working on Interceptors − preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client. postHandle() method − This is used to perform operations before sending the response to the client. afterCompletion() method − This is used to perform operations after completing the request and response. Observe the following code for a better understanding − @Component public class ProductServiceInterceptor implements HandlerInterceptor { @Override public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } @Override public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {} } You will have to register this Interceptor with InterceptorRegistry by using WebMvcConfigurerAdapter as shown below − @Component public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter { @Autowired ProductServiceInterceptor productServiceInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(productServiceInterceptor); } } In the example given below, we are going to hit the GET products API which gives the output as given under − The code for the Interceptor class ProductServiceInterceptor.java is given below − package com.tutorialspoint.demo.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @Component public class ProductServiceInterceptor implements HandlerInterceptor { @Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(“Pre Handle method is Calling”); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println(“Post Handle method is Calling”); } @Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception { System.out.println(“Request and Response is completed”); } } The code for Application Configuration class file to register the Interceptor into Interceptor Registry – ProductServiceInterceptorAppConfig.java is given below − package com.tutorialspoint.demo.interceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Component public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter { @Autowired ProductServiceInterceptor productServiceInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(productServiceInterceptor); } } The code for Controller class file ProductServiceController.java is given below − package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.exception.ProductNotfoundException; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId(“1”); honey.setName(“Honey”); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId(“2”); almond.setName(“Almond”); productRepo.put(almond.getId(), almond); } @RequestMapping(value = “/products”) public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } } The code for POJO class for Product.java is given below − package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } The code for main Spring Boot application class file DemoApplication.java 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 shown here − <?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 shown here − 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”) } You can create an executable JAR file, and run the Spring Boot application by using the below Maven or Gradle commands. For Maven, use the command as shown below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the command as shown below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. You can run the JAR file by using the following command − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080 as shown below − Now hit the below URL in POSTMAN application and you can see the output as shown under − GET API: http://localhost:8080/products In the console window, you can see the System.out.println statements added in the Interceptor as shown in the screenshot given below − Print Page Previous Next Advertisements ”;
Spring Boot – Enabling Swagger2 ”; Previous Next Swagger2 is an open source project used to generate the REST API documents for RESTful web services. It provides a user interface to access our RESTful web services via the web browser. To enable the Swagger2 in Spring Boot application, you need to add the following dependencies in our build configurations file. <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> For Gradle users, add the following dependencies in your build.gradle file. compile group: ”io.springfox”, name: ”springfox-swagger2”, version: ”2.7.0” compile group: ”io.springfox”, name: ”springfox-swagger-ui”, version: ”2.7.0” Now, add the @EnableSwagger2 annotation in your main Spring Boot application. The @EnableSwagger2 annotation is used to enable the Swagger2 for your Spring Boot application. The code for main Spring Boot application is shown below − package com.tutorialspoint.swaggerdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableSwagger2 public class SwaggerDemoApplication { public static void main(String[] args) { SpringApplication.run(SwaggerDemoApplication.class, args); } } Next, create Docket Bean to configure Swagger2 for your Spring Boot application. We need to define the base package to configure REST API(s) for Swagger2. @Bean public Docket productApi() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage(“com.tutorialspoint.swaggerdemo”)).build(); } Now, add this bean in main Spring Boot application class file itself and your main Spring Boot application class will look as shown below − package com.tutorialspoint.swaggerdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableSwagger2 public class SwaggerDemoApplication { public static void main(String[] args) { SpringApplication.run(SwaggerDemoApplication.class, args); } @Bean public Docket productApi() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage(“com.tutorialspoint.swaggerdemo”)).build(); } } Now, add the below Spring Boot Starter Web dependency in your build configuration file to write a REST Endpoints as shown below − Maven users can add the following dependency in your pom.xml file − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> Gradle users can add the following dependency in build.gradle file − compile(”org.springframework.boot:spring-boot-starter-web”) Now, the code to build two simple RESTful web services GET and POST in Rest Controller file is shown here − package com.tutorialspoint.swaggerdemo; import java.util.ArrayList; import java.util.List; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class SwaggerAPIController { @RequestMapping(value = “/products”, method = RequestMethod.GET) public List<String> getProducts() { List<String> productsList = new ArrayList<>(); productsList.add(“Honey”); productsList.add(“Almond”); return productsList; } @RequestMapping(value = “/products”, method = RequestMethod.POST) public String createProduct() { return “Product is saved successfully”; } } 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>swagger-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>swagger-demo</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-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</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-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) compile group: ”io.springfox”, name: ”springfox-swagger2”, version: ”2.7.0” compile group: ”io.springfox”, name: ”springfox-swagger-ui”, version: ”2.7.0” } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands. 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 as 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 command shown here − java –jar <JARFILE> Now, the application will start on the Tomcat port 8080 as shown − Now, hit the URL in your web browser and see the Swagger API functionalities. http://localhost:8080/swagger-ui.html Print Page Previous Next Advertisements ”;
Spring Boot – Thymeleaf
Spring Boot – Thymeleaf ”; Previous Next Thymeleaf is a Java-based library used to create a web application. It provides a good support for serving a XHTML/HTML5 in web applications. In this chapter, you will learn in detail about Thymeleaf. Thymeleaf Templates Thymeleaf converts your files into well-formed XML files. It contains 6 types of templates as given below − XML Valid XML XHTML Valid XHTML HTML5 Legacy HTML5 All templates, except Legacy HTML5, are referring to well-formed valid XML files. Legacy HTML5 allows us to render the HTML5 tags in web page including not closed tags. Web Application You can use Thymeleaf templates to create a web application in Spring Boot. You will have to follow the below steps to create a web application in Spring Boot by using Thymeleaf. Use the following code to create a @Controller class file to redirect the Request URI to HTML file − package com.tutorialspoint.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class WebController { @RequestMapping(value = “/index”) public String index() { return “index”; } } In the above example, the request URI is /index, and the control is redirected into the index.html file. Note that the index.html file should be placed under the templates directory and all JS and CSS files should be placed under the static directory in classpath. In the example shown, we used CSS file to change the color of the text. You can use the following code and created a CSS file in separate folder css and name the file as styles.css − h4 { color: red; } The code for index.html file is given below − <!DOCTYPE html> <html> <head> <meta charset = “ISO-8859-1” /> <link href = “css/styles.css” rel = “stylesheet”/> <title>Spring Boot Application</title> </head> <body> <h4>Welcome to Thymeleaf Spring Boot web application</h4> </body> </html> The project explorer is shown in the screenshot given below − Now, we need to add the Spring Boot Starter Thymeleaf dependency in our build configuration file. Maven users can add the following dependency into the pom.xml file − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> Gradle users can add the following dependency in the build.gradle file − compile group: ”org.springframework.boot”, name: ”spring-boot-starter-thymeleaf” The code for main Spring Boot application class file 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 – 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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </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.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”) compile group: ”org.springframework.boot”, name: ”spring-boot-starter-thymeleaf” testCompile(”org.springframework.boot:spring-boot-starter-test”) } 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 below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the command as shown below − 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 given here − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080 as shown below − Now hit the URL in your web browser and you can see the output as shown − http://localhost:8080/index Print Page Previous Next Advertisements ”;
Tracing Micro Service Logs
Spring Boot – Tracing Micro Service Logs ”; Previous Next Most developers face difficulty of tracing logs if any issue occurred. This can be solved by Spring Cloud Sleuth and ZipKin server for Spring Boot application. Spring Cloud Sleuth Spring cloud Sleuth logs are printed in the following format − [application-name,traceid,spanid,zipkin-export] Where, Application-name = Name of the application Traceid = each request and response traceid is same when calling same service or one service to another service. Spanid = Span Id is printed along with Trace Id. Span Id is different every request and response calling one service to another service. Zipkin-export = By default it is false. If it is true, logs will be exported to the Zipkin server. Now, add the Spring Cloud Starter Sleuth dependency in your build configuration file as follows − Maven users can add the following dependency in your pom.xml file − <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-sleuth</artifactId> </dependency> Gradle users can add the following dependency in your build.gradle file − compile(”org.springframework.cloud:spring-cloud-starter-sleuth”) Now, add the Logs into your Spring Boot application Rest Controller class file as shown here − package com.tutorialspoint.sleuthapp; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class SleuthappApplication { private static final Logger LOG = Logger.getLogger(SleuthappApplication.class.getName()); public static void main(String[] args) { SpringApplication.run(SleuthappApplication.class, args); } @RequestMapping(“/”) public String index() { LOG.log(Level.INFO, “Index API is calling”); return “Welcome Sleuth!”; } } Now, add the application name in application.properties file as shown − spring.application.name = tracinglogs The complete code for 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>sleuthapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>sleuthapp</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-sleuth</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-sleuth”) 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, you can use the following command − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the following command − 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 here − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080. Now, hit the URL in your web browser and see the output in console log. http://localhost:8080/ You can see the following logs in the console window. Observe that log is printed in the following format [application-name, traceid, spanid, zipkin-export] Zipkin Server Zipkin is an application that monitors and manages the Spring Cloud Sleuth logs of your Spring Boot application. To build a Zipkin server, we need to add the Zipkin UI and Zipkin Server dependencies in our build configuration file. Maven users can add the following dependency in your pom.xml file − <dependency> <groupId>io.zipkin.java</groupId> <artifactId>zipkin-server</artifactId> </dependency> <dependency> <groupId>io.zipkin.java</groupId> <artifactId>zipkin-autoconfigure-ui</artifactId> </dependency> Gradle users can add the below dependency in your build.gradle file − compile(”io.zipkin.java:zipkin-autoconfigure-ui”) compile(”io.zipkin.java:zipkin-server”) Now, configure the server.port = 9411 in application properties file. For properties file users, add the below property in application.properties file. server.port = 9411 For YAML users, add the below property in application.yml file. server: port: 9411 Add the @EnableZipkinServer annotation in your main Spring Boot application class fie. The @EnableZipkinServer annotation is used to enable your application act as a Zipkin server. package com.tutorialspoint.zipkinapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import zipkin.server.EnableZipkinServer; @SpringBootApplication @EnableZipkinServer public class ZipkinappApplication { public static void main(String[] args) { SpringApplication.run(ZipkinappApplication.class, args); } } 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>zipkinapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>zipkinapp</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>io.zipkin.java</groupId> <artifactId>zipkin-server</artifactId> </dependency> <dependency> <groupId>io.zipkin.java</groupId> <artifactId>zipkin-autoconfigure-ui</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(”io.zipkin.java:zipkin-autoconfigure-ui”) compile(”io.zipkin.java:zipkin-server”) 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 below Maven or Gradle commands − For Maven, use the command given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the command given below − 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 shown − java –jar <JARFILE> Now, the application has started on the Tomcat port 9411 as shown below − Now, hit the below URL and see the Zipkin server UI. http://localhost:9411/zipkin/ Then, add the following dependency in your client service application and point out the Zipkin Server URL to trace the microservice logs via Zipkin UI. Now, add