Tag Archives: java 8

Spring Scheduling Annotations List

After Spring Boot, Spring enhanced with scheduling and Asynchronous annotations which added with methods along with some information about to execute it, and Spring takes care of rest.

These annotations are from the org.springframework.scheduling.annotation package. Below are most common annotations which we use at time of development:

See Also :

Spring Scheduling Annotations


@EnableAsync annotation enable asynchronous functionality in Spring. It must use with @Configuration.

class VehicleFactoryConfig {}

Now, that we enabled asynchronous calls, we can use @Async to define the methods supporting it.


@EnableScheduling annotation enable scheduling in the application. We should always use it in conjunction with @Configuration:

class VehicleFactoryConfig {}

Now we are enabled with Schedule, we can now run methods periodically with @Scheduled.


@Async apply on methods which we want to execute on a different thread, hence run them asynchronously.

void repairCar() {
    // ...

If we apply @Aynch annotation to a class, then all methods will be called asynchronously.

Note: Before applying @Async on method first we need to enabled the asynchronous calls for this annotation to work, with @EnableAsync or XML configuration.


@Scheduled annotation use to execute a method periodically at fixed interval or by Cron like expressions.

For Example : The first execution of the task will be delayed by 5 seconds and then it will be executed normally at a fixed interval of 2 seconds.

@Scheduled(fixedRate = 2000 , initialDelay=5000)
void checkVehicle() {
    // ...

After Java 8 with repeating annotations feature, @Scheduled can mark multiple times on a method with different period or Cron expressions.

For Example : The first execution of the task will be delayed by 5 seconds and then it will be executed normally at a fixed interval of 2 seconds and cron expression will execute on Monday to Saturday on 12 PM.

@Scheduled(fixedRate = 2000)
@Scheduled(cron = "0 * * * * MON-SAT")
void checkVehicle() {
    // ...


  • Before applying @Scheduled on method first we need to enabled the scheduling calls by applying @EnableScheduling configuration. that the method annotated with @Scheduled should have a void return type.
  • The method having @Scheduled should have a void return type.


@Schedules annotation use to specify multiple @Scheduled rules.

  @Scheduled(fixedRate = 2000),
  @Scheduled(cron = "0 * * * * MON-SAT")
void checkVehicle() {
    // ...

Note: Same feature can achieve  since Java 8 with repeating annotations as described above.

Java : Annotation Tutorial

What is Annotation?

Annotations, a form of metadata, provide data about a program that is not part of the program itself and  no direct effect on the operation of the code they annotate.

See Also :

Where to use Annotation?

Annotation can be use on following cases:

  1. Applied as Declaration : Annotation can be use as declaration of classes, fields, methods and other program elements.
  2. Information for the compiler : Annotations can be used by the compiler to detect errors or suppress warnings.
  3. Compile-time and deployment-time processing : Software tools can process annotation information to generate code, XML files, and so forth.
  4. Runtime processing : Some annotations are available to be examined at runtime.
  5. Applied as Type : After Java 8+, annotation can we use as type also.

Points to remember

  • The at sign character (@) indicates to the compiler that what follows is an annotation.
  • If the annotation has no elements, then the parentheses can be omitted.
  • The annotation type can be one of the types that are defined in the java.lang or java.lang.annotation packages.
  • When annotation used as declaration, as convention each annotation often appears on its own line.

Format of Annotations

Below are some types of annotation and uses:

Pre-Defined Annotation without values

public class Employee

public String toString()
return "FacingIssuesOnIT";

Annotations with multiple values

name = "Saurabh Gupta",
date = "06/04/2017"
class MyTestClass() { ... }

Annotations with single value

@SuppressWarnings(value = "unchecked")
void myTestMethod() { ... }


//if there is only one value avoid use fields to make more clean code
void myTestMethod() { ... }

Use of Multiple annotation

@Author(name = "Saurabh Gupta")
class MyTestClass { ... }

Repeatating Annotation (Java 8+)

If the annotations have the same type, then this is called a repeating annotation:

@Author(name = "Saurabh Gupta")
@Author(name = "Navin kumar")
class MyTestClass { ... }

Annotation as Type (Java 8+)

After Java 8 expended scope of using Annotation as below:

Class instance creation expression:

new @Interned MyTestClass();

Type cast:

myString = (@NonNull String) str;

Implements clause:

class UnmodifiableList implements
@Readonly List { ... }

Thrown exception declaration

void monitorSpeed() throws
@Critical SpeedException { ... }
This form of annotation is called a type annotation.

Now you have learn about Annotations , use of annotations  and enhancement in scope of annotations after java 8+. Now we will talk about predefined annotations and creation of custom annotation.

Predefined Annotation

  • @Deprecated : @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation. When an element is deprecated, it should also be documented using the Javadoc @deprecated tag,
  • @override : @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. use from Inheritance and interface.
  • @SuppressWarnings : @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate.
    // use a deprecated method and tell
    // compiler not to generate a warning
    void useDeprecatedMethod() {
    // deprecation warning - suppressed
    @SuppressWarnings({"unchecked", "deprecation"})
  • @SafeVarargs: @SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargs parameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.
  • @FunctionalInterface: @FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.

Annotations that apply on other annotations (Meta annotation). These annotations defined in java.lang.annotation.

    • @Retention:  @Retention annotation specifies how the marked annotation is stored:
      1. RetentionPolicy.SOURCE : Retained only in the source level and is ignored by the compiler.
      2. RetentionPolicy.CLASS : Retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
      3. RetentionPolicy.RUNTIME : Retained by the JVM so it can be used by the runtime environment.
    • @Documented: Indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.).
    • @Target: Marks another annotation to restrict what kind of Java elements that annotation can be applied to. A target annotation specifies one of the following element types as its value:
      1. ElementType.ANNOTATION_TYPE: applied to an annotation type.
      2. ElementType.CONSTRUCTOR: applied to a constructor.
      3. ElementType.FIELD : applied to a field or property.
      4. ElementType.LOCAL_VARIABLE : applied to a local variable.
      5. ElementType.METHOD : applied to a method-level annotation.
      6. ElementType.PACKAGE : applied to a package declaration.
      7. ElementType.PARAMETER: applied to the parameters of a method.
      8. ElementType.TYPE: applied to any element of a class.
    • @Inherited : This annotation applies only to class declarations. @Inherited annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class’ superclass is queried for the annotation type.
  • @Repeatable: @Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use.

Custom Annotation

We can define our own annotation i.e called as custom annotation. We have to follow below steps while creation of custom annotation:

  1. Create custom annotation with @interface.
  2. Define type of annotation, retention policy and where need to implement that.
  3. define values of annotation. if required set some default values by using keyword as default.

Here is custom annotation for document the class changes

 package com.common.annotations;

import java.lang.annotation.Documented;

public @interface ChangeRecord {
	   String author();
	   String date();
	   int currentRevision() default 1;
	   String lastModified() default "N/A";
	   String lastModifiedBy() default "N/A";
	   // Note use of array
	   String[] reviewers();

Use of custom annotation over documentation of class changes.

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved
package com.common.annotations;

import java.lang.annotation.Annotation;

	author = "Saurabh Gupta",
	date = "3/4/2019",
	currentRevision = 2,
	lastModified = "5/4/2019",
	lastModifiedBy = "Gaurav Gupta",
	reviewers = {"Rajkumar", "Raghav", "Rajesh"}
public class CustomAnnotationExample {

	public static void main(String[] args) {


Repeatable Annotation Example

Java 8+ introduced repeatable annotation so that same annotation can be use multiple time. For example create custom annotation to implement as repeatable annotation.

Create Custom Repeatable Annotation

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved
package com.common.annotations;
import java.lang.annotation.Repeatable;
* Repeatable annotation introduced in <strong>java 8+</strong> to use repeatative task */

public @interface Schedule {
String dayOfMonth() default "first";
String dayOfWeek() default "Mon";
int hour() default 2;

Create of array of repeatable annotation

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved
package com.common.annotations;
public @interface Schedules {
Schedule[] value();

Use of repeatable annotation

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved */
package com.common.annotations;
import java.util.Date;
public class RepeatableAnnotationExample {
    public static void main(String[] args) {
	// TODO Auto-generated method stub

@Schedule(dayOfWeek="Fri", hour=23)
   public void doPeriodicCleanup() {
     System.out.println("Clean up started at :"+new Date());

Annotation Exceptions

Below are some annotation related exceptions which occurred at runtime:

Reflection for Annotation

In Java 8+ introduced some new reflection apis to retrieve annotation related information from different elements type like classes, interfaces, method, type etc.

Follow below link to get all  reflections apis for annotation:

Java : Reflection for Annotations


Here you have learned about annotation in depth knowledge:

  • Annotation and pre-defined annotation and uses.
  • Scope of annotations in Java 8+.
  • Implementation of annotation.
  • Custom Annotation with exmaple
  • Repeatable  Annotation with example.
  • Reflection for Annotations (Java 8+) APIs.
  • Exception occurred by annotations.

[Solved] java.time.DateTimeException: Invalid date ‘February 29’ as ‘2014’ is not a leap year

java.time.DateTimeException occurs while calculating Date and Time in java.time classes. This exception is used to indicate problems with creating, querying and manipulating date-time objects.


  • DateTimeException(String message) : Constructs a new date-time exception with the specified message.
  • DateTimeException(String message, Throwable cause) : Constructs a new date-time exception with the specified message and cause.

Sample Code

 try {
// Here with throw DateTimeException if pass as Invalidate Date
// format
LocalDate lastDay_2014 = LocalDate.of(2014, Month.FEBRUARY, 29);
System.out.println("Specific Date=" + lastDay_2014);<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
} catch (DateTimeException ex) {

Output Message

java.time.DateTimeException: Invalid date 'February 29' as '2014' is not a leap year
    at java.time.LocalDate.create(Unknown Source)
    at java.time.LocalDate.of(Unknown Source)
    at datetime.Java8DateTime.localDateAPI(Java8DateTime.java:157)
    at datetime.Java8DateTime.main(Java8DateTime.java:32)


Here with throw DateTimeException if pass as Invalidate Date. For above example passing date as 29 as we know February month only have 29 days in month of leap year. Here year as we passing is 2014 which is not leap year.


To solve this issue pass max date for february month after validating leap year from below API.

LocalDate today = LocalDate.now();
//LocalDate.isLeapYear()this api will return true or false after checking for leap year

boolean LocalDate.isLeapYear() : Checks if the year is a leap year, according to the ISO proleptic calendar system rules.

More Issues Solution

For more other JAVA/JDBC issues solution follow link JAVA/JDBC Issues.