Thursday, March 7, 2019

Spring boot note

1. Log
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

By default, all logs will print on the console window and not in the files. 
You can specify the own log file name using the property shown below −
logging.file = /var/tmp/mylog.log

The code given below shows how to add the slf4j logger in Spring Boot main class file.
private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class);
logger.info("this is a info message");
2. Exceptions
he @ControllerAdvice is an annotation, to handle the exceptions globally.
@ControllerAdvice
public class ProductExceptionController {
   @ExceptionHandler(value = ProductNotfoundException.class)
   public ResponseEntity<Object> exception(ProductNotfoundException exception) {
      return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
   }
}
3. Rest Template
Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods.

4. Scheduling
The @EnableScheduling annotation is used to enable the scheduler for your application. 
The @Scheduled annotation is used to trigger the scheduler for a specific time period.
@Scheduled(cron = "0 * 9 * * ?")
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);
   }
}
5. Actuator
Spring Boot Actuator provides secured endpoints for monitoring and managing your Spring Boot application. 
In the application.properties file, we need to disable the security for actuator endpoints.
management.security.enabled = false

/metricsTo view the application metrics such as memory used, memory free, threads, classes, system uptime etc.
6. Oauth2 with JWT

No comments:

Post a Comment